Wednesday, May 11, 2016

Web-based Notifications Implementation

Hi, The following code samples may help you in implementing web-based notifications in your portal/website without using any third party library.

Notification Window CSS Code:
Notification Window UI Code:
Notification window UI will look like, as follows
JavaScript Code to View / Hide Notification Window:
Expanded notification window will be look like, as follows

Monday, March 14, 2016

Shell Script to Extract Email ids from Website URL

It is always tedious work to extract e-mail ids from websites for publicity purpose. So I created a shell script which automate the extraction of mail ids from URLs.

#!/bin/bash

# SCRIPT NAME: mail_id_extractor_from_url.sh

# DESCRIPTION: This script takes a list of seed URLs and extracts all sub URLs and referenced URLs from seed URLs. Visits all sub and referenced URLs of seed URLs and extracts mail ids.

# USAGE: bash mail_id_extractor_from_url.sh website_list.txt
# website_list.txt file contains all seed URLs to extract mail ids.

#AUTHOR: Reniguntla S

filename="$1"
while read -r seed_url
do
    name="$seed_url"
    lynx -dump $seed_url | grep "http" >> sub_urllist0.txt
done < "$filename"

cat sub_urllist0.txt | awk '{print $2}' > sub_urllist1.txt
sort sub_urllist1.txt | uniq -u > sub_urllist.txt
rm sub_urllist0.txt sub_urllist1.txt
echo "Extraction of sub URLs of seed URLs done"

mode=1
if [ "$mode" -eq "1" ];then
echo "Be patient, It will take some time :-)"
cat sub_urllist.txt | while read url
do
echo $url
curl $url > url_text.txt
grep -E -o "\b[a-zA-Z0-9.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9.-]+\b" url_text.txt >> mailids.txt
done
fi

sort mailids.txt | uniq >> extracted_mail_list.txt
rm mailids.txt url_text.txt
echo "Email ids extraction done. Check extracted_mail_list.txt file"
exit 0

# End of script


Thursday, March 3, 2016

Short Term Courses on Data Science

Call for Participation
Short-term courses on Data Science
CDAC, Kharghar, Navi Mumbai

We are living in a Data Age. Data is being continuously generated and consumed in various formats, and sizes from a number of varied sources. This data can be a big asset if stored, processed and analysed efficiently in real time with the help of intelligent algorithms. There is a growing interest to utilize such data for the improvement of business, health, education, society, etc. There are many ways to process and analyse such data spanning techniques like data visualization, text analysis, predictions and recommendations etc. Applications of these techniques can give companies and organisations valuable insights leading to competitive advantage, efficient service delivery and above all customer satisfaction. And so the demand for skilled resources in these fields is growing day by day.


With this view, CDAC, Mumbai is announcing the following short-term courses in Data Science and Machine Learning.
--Using R for data visualization and analytics
--Text Analytics
--Predictive Analytics and Recommender Systems
For more details and registration, please visit at http://www.kbcs.in/datascience.



Wednesday, September 9, 2015

Accessing MySql Database in R for Analytics

Step-1: Open / connect to your MySql by running following command.                                        
Step-2: Create test database and ensure test database created or not as shown in following figure.














Step-3: Now create a table student with student id and total marks as its fields as shown in following figure.












Step-4: Insert some data into student table as shown below.


Now student data is ready in MySQL. Now we will see how we can access student data in R.

Step-5: Before installing RMySQL package in R make sure you installed mysql-connector-c. To install mysql-connector-c run the following command in terminal.

sudo apt-get install libmysqlclient-dev    // on debian or ubuntu

yum install mysql-devel   // on RHEL, Cent OS, Fedora

Step-6: Now Open your RStudio and install MySQL package. To Install MySQL package click on Tools ->Install Packages...

Step-7: Now write a R Script as shown in following picture to read student data from MySQL. For more details please read the comments mentioned in below R code.


Tuesday, September 8, 2015

Fixing GPG NO_PUBKEY Error

              By default R version 2.14.1 available on my Ubuntu 12.04 LTS system. I decide to generate some interactive graphs in R but I was not able to generate them because 2.14.1 is very old version of R. So, I decided to upgrade my R from 2.14.1 to 3.2.2 version. So, added an entry into sources.list as shown in following picture.

List of R mirrors can be found at https://cran.r-project.org/mirrors.html.

After made an entry into sources.list and update the system by running following command.

sudo apt-get update

This update command some times throws an error like "GPG error NO_PUBKEY". We can fix this error using y-ppa-manager. To install y-ppa-manager run the following list of commands.

sudo add-apt-repository ppa:webupd8team/y-ppa-manager  // adding repository for y-ppa-manager

sudo apt-get update // updating repository

sudo apt-get install y-ppa-manager // Installing y-ppa-manager

After installing y-ppa-manager, start y-ppa-manager by typing the same in the terminal and it will display GUI as shown below.























Click on Advanced Option and then Select "try to import all missing GPG keys" and click on OK as shown in following figure. It will fix the error "GPG error NO_PUBKEY". Run sudo apt-get update again to see error is fixed or not.


Wednesday, August 26, 2015

R and JRI Integration with Java for Analytics

Different ways(rJava with JRI, RServ, RCaller, Renjin) are there to integrate R with Java to perform some analytic work inside the Java (Servlet / controller). In this post I would like to show, how you can integrate rJava and JRI with java to run R code inside Java.

JRI Integration with Java: JRI stands for Java-R Interface and It is a part of rJava. Using rJava we can manipulate Java objects inside R using JNI (Java Native Interface) which is the natural way of calling compiled binary code in Java but JRI is reverse of it. In JRI we can call R inside Java. This library has some merit among others, in means of full interoperability between R and Java using callbacks. It is robust for large scale projects, however, it is painless at start-up process for relatively small projects.

To Install R on debian based systems run the following command
sudo apt-get install r-base-dev

Now to install rJava package in R run the following command
sudo apt-get install r-cran-rjava

Other wise you can run following command in R to install rJava
install.packages("rJava")

Once you install the R and rJava, to find the location of JRI inside rJava run the following command in R.
system.file("jri",package="rJava")







Now export R_HOME=/usr/lib/R, LD_LIBRARY_PATH=/usr/lib/R/site-library/rJava/jri into environment and add both of them in the Java library path also.

Now open your eclipse create a simple Java project "JRITest" with the below mentioned code. Before running the code in eclipse set R_HOME and LD_LIBRARY_PATH environment variables in eclipse. For setting up environment variables in eclipse

Right Click on Project -> Run As -> Run Configurations -> Environments then add environment variables with their values as shown below.





Sample Code To Test JRI In Java:
Sample Input Output:


Tuesday, June 23, 2015

Problems Faced By Motor Disability Persons In HCI

                    Computer trainers often comment on the fact that conventional devices are hard to use whose fingers might not be as steady or mobile anymore. Moreover Limited muscular control can cause lack of coordination or involuntary movement or impede movement altogether. Wide range of problems are faced by physical / motor disability persons in accessing computers, Some of them are as follows.

  • Pressing key board keys continuously- A physically challenged user can find pressing key board keys continuously for typing to be laborious due to limitations in motor control.
  • Long key press problem- An alphanumeric key is unintentionally pressed by differently enabled user for longer than the default key repeat delay because of slow typing speed.
  • Additional key press problem- During typing, A key adjacent to the intended key may be activate accidentally.
  • Key bounce problem- The end user may unintentionally presses the intended key more than once.
  • Difficulty in using hot keys- Some times it is not even easy for normal users to use hot keys. So, obviously motor disabilities find it more difficult to use SHIFT, CTRL and ALT keys with the combination of any other Keys.
  • Keys transposition error- When two keys are typed in the wrong order, a transposition error has occurred. Motor disabilities usually face this problem.
  • Mouse pointing problem- Mouse pointing is there in almost every operation of mouse like selecting one icon, among so many icons and closing an active window with mouse etc. So, pointing is the most fundamental mouse operation and also one of the most difficult for motor disabilities because Mouse pointing involves moving pointer in a desired direction and positioning at required place.
  • Navigation problem- For example in Debian based systems, if user wants to open gedit text editor, then user needs to navigate through Applications ->Accessories ->gedit. This requires three mouse button clicks which is inconvenient for some kind of motor disabilities.
  • Selection of text- involves to hold down mouse button and drag or hold down Shift key and press right arrow continuously. So, physically challenged people face problem in selection of text.
  • Hand-eye coordination problem- Hand-eye coordination is the ability of the vision system to coordinate the information received through the eyes to control, guide, and direct the hands in the accomplishment of a given task. Some kind of motor disabilities suffer from this problem because their hands doesn't give them enough support to process information received by eyes.
  • Drag and drop problem- Once a drag had been started, the most common difficulty is in raising the mouse button in the correct position at the end of the drag. Another common problem is in holding down the mouse button while moving the mouse to the target.

Sunday, June 14, 2015

C and C++ Code Counter - A Software Metric Tool

         CCCC ( C and C++ Code Counter) a software metrics tool. CCCC  analyses and  reports measurements of source code in C, C++, and Java. It was developed to augment programmers' instinctive application of  numeric  rules  of thumb about what constitutes high or low quality products with an automated analysis tool. CCCC processes the files listed on its command line.  If the  file names include ‘-’, read a list of files from standard input.

         CCCC will provide the following details/information of the code modules.
  • MVG = McCabe's Cyclomatic Complexity
    A measure of the decision complexity of the functions which make up the program.The strict definition of this measure is that it is the number of linearly independent routes through a directed acyclic graph which maps the flow of control of a sub-program. The analyser counts this by recording the number of distinct decision outcomes contained within each function, which yields a good approximation to the formally defined version of the measure. 
  • NOM = Number of modules
    Number of non-trivial modules identified by the analyser. Non-trivial modules include all classes, and any other module for which member functions are identified.
  • LOC = Lines of Code
    Number of non-blank, non-comment lines of source code counted by the analyser.
  • COM = Lines of Comments
    Number of lines of comment identified by the analyser
  • L_C = Lines of code per line of comment
    Indicates density of comments with respect to textual size of program
  • M_C = Cyclomatic Complexity per line of comment
    Indicates density of comments with respect to logical complexity of program
  • IF4 = Information Flow measure
    Measure of information flow between modules suggested by Henry and Kafura. The analyser makes an approximate count of this by counting inter-module couplings identified in the module interfaces.

Installation: CCCC is included in most of the linux operating systems repositories. You just need to type the following command to install CCCC on debian based systems.

- sudo apt-get install cccc

If the tools not available in your linux system repository you can download it from http://sourceforge.net/projects/cccc/ .

Usage: To know the usage of CCCC type the command man cccc in your terminal. A typical command of cccc usage is as follows.

- cccc your_sourcefile_name.cpp

The above command will generate a html page with name cccc.html in your present working directory, which provides the above mentioned information of your modules in the your_sourcefile_name.cpp. A sample cccc.html screen shot is as follows.


Wednesday, May 20, 2015

Workshop on Oracle 11g

Workshop on Oracle 11g - Database Design using Object Oriented Features: If you are a database enthusiast, then get the maximum benefit from this one day workshop on Oracle 11g by Mr. Sameer Dehadrai. More details can be found in the following picture /  brochure and the Registration can be done at: http://tinyurl.com/lolyj7h

Monday, May 18, 2015

Dooms Day Algorithm to Find Week Day of Given Date

        Using Dooms Day Algorithm / Rule any one can find the week day of given date between 1800 - 2199 years. So, The dooms day rule / formula is as follows



Dooms day = Anchor Day + [Year/12] + Remainder[Year/12] + [Remainder[Year/12]]/4

If the given date's year falls,

between 1800-1899, The Anchor Day is Friday
between 1900-1999, The Anchor Day is Wednesday
between 2000-2099, The Anchor Day is Tuesday
between 2100-2199, The Anchor Day is Sunday 

In the Above formula Year is last 2 digits of given date's year and in above equation solving wherever we get decimal values we have to take integer values only.

Once we get the dooms day for the given date's year using above formula, that dooms day will fall on last day of February (if given year is normal year on Feb 28, otherwise Feb 29), April 4 (4/4), June 6 (6/6), August 8 (8/8), October 10 (10/10) and December 12 (12/12).

Example: Lets find the week day of August 15, 1947.

The given date's year 1947 falls between 1900-1999 so the Anchor day is Wednesday.

Dooms day = Wednesday + [47/12] + Remainder[47/12] + [Remainder[47/12]]/4

Dooms day = Wednesday + 3 + 11 + 2

Dooms day = Wednesday + 16 (Divide this number by 7 and take remainder to find number of odd days)

Dooms day = Wednesday + 2 = Friday.

So the Dooms day for year 1947 is Friday and It will fall on August 8 as I said earlier. So, If August 8 is Friday after one week i.e., on August 15 is also going to be Friday.

So finally August 15, 1947 is Friday :-).

Thursday, January 8, 2015

Recursive Makefile for Sub-Directories

                 As we know, compiling is very tedious work, specially when we want to include several source files and have to type the compiling command every time we want to do compiling. It is even more difficult when our source files are in nested sub- directories.  To escape from these tedious work most of the people create Makefile. Makefile is a special format file that together with the make utility will help to automatically compile our several source files. The advantage of using Makefile is that it performs incremental compilation.

              Here, I would like to share a Makefile which is capable of compiling source files presented in nested sub-directories, creating objects of each source file in its directory and creating a binary from all object files presented in nested sub-directories. (NOTE: if you are using following Makefile, make sure to use tab at required places)

Makefile
***********

PREFIX            = /usr/local
INCLUDE        = /usr/include/X11/
PWDDIR          = $(shell pwd)
CXX                  = g++
RM                   = rm -vf
CONSTANTS   = -D__GXX_EXPERIMENTAL_CXX0X__       
CPPFLAGS      = -O0 -g3 -Wall -c -fmessage-length=0 -fpermissive -std=c++0x
LDFLAGS        = -lX11 -lXi -lXtst -lm
BINARY           = gframework_demo
DEPS               = $(shell find . -name '*.hpp')
SRCFILES       = $(shell find . -name '*.cpp')
OBJFILES        = $(SRCFILES:%.cpp=%.o)

all: $(BINARY)

$(BINARY): $(OBJFILES)
    $(CXX) -I$(INCLUDE) -o "$(BINARY)" $(OBJFILES) $(LDFLAGS)

%.o: %.cpp $(DEPS)
     $(CXX) $(CONSTANTS) -I$(INCLUDE) -I"$(PWDDIR)" $(CPPFLAGS) -c $< -o $@

clean:
    $(RM) $(shell find . -name '*.o') *~
    $(RM) $(BINARY)

install: $(BINARY)
    install -m 0755 $(BINARY) $(PREFIX)/bin
       
.PHONY: install

Wednesday, November 12, 2014

Drupal7 Installation and Website Development


For installing drupal7 we need to install LAMP(Linux, Apache, MySql, Php) server. I am assuming that you already installed any Debian based Linux(L) OS like Ubuntu. Run the following commands in terminal to install LAMP server.

Installing Apache(A):

To install apache2 run following command.

- sudo apt-get install apache2

To check apache2 installed, type the URL http://localhost/ in web browser.


Installing Php(P):

To install Php5 run following command.

- sudo apt-get install php5 libapache2-mod-php5

- sudo /etc/init.d/apache2 restart

To check php5 installed properly or not, create test.php in /var/www/ with code shown in screenshot.




Now type http://localhost/test.php in web browser, it will display the information of installed Php as shown in following screenshot.























Installing MySql(M):

To install MySql run following command in terminal.

- sudo apt-get install mysql-server

During MySql server installation do not forget to enter root user password.












Run following command to install phpadmin in terminal.

-  sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin

During phpadmin installation select apache2 as default to run phpadmin using apache2, by pressing space tab as shown in screenshot.

During phpadmin installation setup required passwords also.

Now LAMP server is installed. Do the following settings also.

- Uncomment extension=msql.so in /etc/php5/apache2/php.ini file as shown in following screenshot.


- Add  ServerName localhost in /etc/apache2/httpd.conf file.

Creating Required MySql Database:

 Log into MySql using following command

- mysql -u root -p

Then create Required database using following command

- create database drupaldb;

Then create a user to access that database using following command

- create user 'user1'@'localhost';

Set password for created user user1

- update mysql.user set password=password('PassWord') where user='user1';

Grant all privileges to user1 on drupaldb using following command

- grant all privileges on drupaldb.* to 'user1'@'localhost';

Then flush all privileges using following command

- flush privileges;

Installing Drupal7:

Download drupal7 using following command

- wget http://ftp.drupal.org/files/projects/drupal-7.23.tar.gz

Now move downloaded drupal-7.23.tar.gz to /var/www/drupalsite folder and extract there itself. You need to create drupalsite folder in /var/www/. Change the owner of drupalsite by running following command.

- chown -r www-data.www-data drupalsite

Now make sure your apache HTTP listens to port 8001 (if you want you can use any other port also). To listen port 8001, enter Listen 8001 in /etc/apache2/ports.conf file as shown in following screenshot.


Now copy the contents of /etc/apache2/sites-available/default to /etc/apache2/sites-available/drupalsite and add the content shown in following screenshot to /etc/apache2/sites-available/drupalsite file.


Now run the following bunch of commands to take affect of made changes / settings.

- sudo a2ensite /etc/apache2/sites-available/drupalsite
- sudo /etc/init.d/apache2 reload
- sudo a2enmod vhost_alias rewrite
- sudo /etc/init.d/apache2 reload

 Now whatever setup needed for installation of drupal7 is ready. Type http://localhost:8001/install.php URL in web browser and you will see the page as shown in following screenshot.



Now click on Save and continue, in the next screen select english as language. After that, in database configuration enter database details, which you have created in mysql as shown in following screenshot.

In the next step enter all the details like site name, site maintenance e-mail and site maintenance account details.

 Once you enter the above details your drupal site is ready.

Now click on Visit your new site to see your site.

Now your basic drupalsite is ready. By using your site maintenance account you can create new content, new modules etc.

http://accessibledesktop.in is an example site developed using drupal7.

Thursday, October 16, 2014

Calibrating Wacom BAMBOO ONE CTE-660 to Particular portion of Screen

I was working on calibrating Wacom tablets (Wacom Bamboo One CTE-660) to particular portion of the desktop screen. Initially I implemented my own mechanism by editing wacom driver configuration files to calibrate but lately I found xsetwacom utility which is very useful to query or change properties on the devices loaded by the wacom driver. The modification of properties happens at runtime and is not persistent through X server restarts.
Wacom Bamboo One CTE-660
  To install xsetwacom, first of all download it from Here and extract the downloaded file & follow the instruction given in INSTALL file.

Once you install xsetwacom utility, to calibrate(map) wacom tablet to left top most portion of 500X500 area of your screen, run the following command.

xsetwacom set "Wacom Bamboo1 5x8 stylus" MapToOutput 500X500+0+0

To calibrate(map) wacom tablet to entire scree run the following command

xsetwacom set "Wacom Bamboo1 5x8 stylus" MapToOutput VGA1

 The following program creates a xwindow & by pressing 'm' key calibrates(map) Wacom Bamboo1 5x8 stylus to the created window and by pressing 'u' calibrates Wacom Bamboo1 5x8 stylus to entire screen.


#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <X11/extensions/shape.h>
#define NIL (0)

int main()
{
  char *window_name = (char*)"gem input window";
  Display *dpy = XOpenDisplay(NIL);
  int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));
  Window w = XCreateSimpleWindow(dpy, RootWindow(dpy, DefaultScreen(dpy)), 0, 0, 500, 500, 0, whiteColor, whiteColor);
  XSelectInput(dpy, w, ButtonPressMask| PointerMotionMask| LeaveWindowMask| EnterWindowMask| ButtonReleaseMask );
  XStoreName(dpy, w, window_name);
  XMapWindow(dpy, w);
  for(;;) {
   XEvent e;
   XNextEvent(dpy, &e);
   if(e.xany.window == w)
     {
       switch(e.type)
        {
         case KeyPress: 

        if (e.xkey.keycode == XKeysymToKeycode(dpy, XK_m))
        {
        printf("\n Calibration to 500X500 Done");
        system("xsetwacom set \"Wacom Bamboo1 5x8 stylus\" MapToOutput 500X500+0+0");
        }
        if (e.xkey.keycode == XKeysymToKeycode(dpy, XK_u))
        {
          printf("\n Calibrating to entire screen Done");
          system("xsetwacom set \"Wacom Bamboo1 5x8 stylus\" MapToOutput VGA1");
        }
        if (e.xkey.keycode == XKeysymToKeycode(dpy, XK_e))
        XDestroyWindow(dpy, w);
        break;                  
     }
    }
 }
  return 0;

}

Thursday, September 18, 2014

Replacing Pronunciation Dictionary of Acoustic Model in Sphinx4


Lets say, We are creating a Speech Recognition system for recognising computer related words only.  Now, I will tell you, How to create pronunciation dictionary for computer related words and how to add that dictionary in acoustic model. In this example I am using WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar acoustic model.

CREATING PRONUNCIATION DICTIONARY:

Step 1 :
Create a plain text file "computer.txt", and Write down all words related to computer in that text file.



Step 2 : Now go to this link : http://www.speech.cs.cmu.edu/tools/lmtool.html

Step 3 : After Opening above link, go to "Sentence corpus file" section and then browse "computer.txt" file and then click "Compile Knowledge Base".








Step 4 : Wait for few seconds/Minutes, once the dictionary is created, click on "Dictionary" link and save that .DIC file.

 










Now pronunciation dictionary for computer related words is ready. Now We will see how to include this pronunciation dictionary in acoustic model.

ADDING PRONUNCIATION DICTIONARY TO ACOUSTIC MODEL

Step 5 : Locate WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar file in sphinx4. (Generally can be find at location /sphinx4-1.0beta6-bin/sphinx4-1.0beta6/lib).

Step 6 : Extract WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar

 Step 7 : Open "cmudict.0.6d" which is located in extracted folder /sphinx4-1.0beta6-bin/sphinx4-1.0beta6/lib/ WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz/dict/ 

Step 8 : Now copy data from .DIC file created in Step 4 and paste it into "cmudict.0.6d" file and save. 











Step 9 : Now create the JAR file and keep the extracted hierarchy back as it was and the name of JAR file should be WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar.

Now acoustic model with pronunciation dictionary of computer related words is ready.

Now, remove old "WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar" file from Project’s CLASSPATH and add newly created "WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar" file instead of it.

That’s it ! Now We are done.  Now Sphinx will recognize all computer related words which we wrote in "computer.txt" file.

Thursday, July 31, 2014

Unix Shell Programming Basics

Shell Program
A shell program or shell script is a collection of Shell commands to perform a particular task .

Examples:
  • Unix Shell scripts (ksh, csh, bash, sh)
  • Python
  • perl
  • VBScript
  • Java Script
  • Apple Script etc.

Uses of Shell Programming
  • To combine lengthy and repetitive sequences of commands into a single, simple command.
  • To create new commands using combinations of pre-existing commands.
  • To automate the process of setting up and running applications.
Shell Program structure
  • Any text editor can be used to type shell program.
  • #! /bin/sh
    # this is a comment
    body of program
    exit 0 
  • #! /bin/sh indicates to other users to run the script using /bin/sh 
  • #! /bin/sh is called as shebang or hashbang 
  • Comment line starts with #  
  • exit 0 represents the end of script
Steps involved in Shell Script
    Step-1: Type shell program in a text file 
    Step-2: Save file with .sh extension
    Example: FileName.sh 
    Step-3: Make FileName.sh Executable for all users using 'chmod 755 FileName.sh
    Step-4: Run script using ./FileName.sh

Shell Script Examples

#! /bin/sh
#Script Name: Run.sh
#Purpose: to run hello.c file
gcc -o hello hello.c
./hello
exit 0

#! /bin/sh
#Script Name: UpdateUpgrade.sh
#Purpose: To update & upgrade debian #based system
apt-get update
apt-get upgrade
reboot
exit 0

Note: You need super user privileges to run UpdateUpgrade.sh script

Assignments-1
  • Write a shell script to display your name on screen (Time: 1 Min) 
  • Write a shell script to remove CDAC directory, whose absolute path is /home/reniguntla/CDAC (Time: 2 Min) 
  • Write a shell script to display all lines contains “sh” in file UpdateUpgrade.sh (Time: 2 Min)


Shell Script Variables
  • By deafault all variables in shell script are strings.

  • #! /bin/sh
    #Script Name: Variable.sh
    #Purpose: To demonstrate variables
    x=Hello
    echo "$x"
    y="Hi"
    echo "$y"
    z="How are you?"
    echo "$z"
    exit 0
  • Output: Hello
                      Hi
                      How are you?


Quoting of variables

#! /bin/sh
#Script Name: Quote.sh
#Script purpose: To demonstrate variable with #quotations
x=Hello
echo $x
x=”Hello”
echo $x
x=”Hello Mr.L”
echo $x
echo '$x'
exit 0

OutPut: Hello
              Hello
             Hello Mr.L
             $x

Assignments-2
  • Write a shell script to print your name and student id on screen using variables? (1 Mins) 
  • Write a shell script to swap 2 numbers using temporary variable? (2 Mins)

Shell Script Binary Operators 
 

Shell Script Binary Operators Example

#!/bin/sh
#Script Name: BinaryOp.sh
#Purpose: Demonstration of binary operators
a=10
b=20
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
exit 0

OutPut: a+b:30
               a-b:-10
               a*b:200
               b/a:2
               b%a:0

Shell Script Relational Operators


Shell Script Boolean Operators

Note: Explore string operators yourself

Shell Script File Test Operators
 

Reading Input From User

To read input we use read command 
 
#! /bin/sh
#Script Name: InputRead.sh
#Purpose: To demonstrate read command
echo “Enter your name?”
read MyName
echo “Your name is $MyName”
exit 0

OutPut: Enter your name ?
               Reniguntla
               Your name is Reniguntla


Assignments-3

Write a shell script to read your name, roll number, marks in 4 subjects. Display your name, roll number, average of 4 subjects & percentage on screen. (3 Min)

Shell Script Parameters

All command line parameters / arguments of a shell script can be accessed via $1, $2, $3,..., $9, ${10}, ${11}...

$# holds the number of parameters passed

$@ Holds A list of all parameters in a single variable

$* also holds all parameters

$0 holds the name of the script

Shell Script Parameters Example

#!/bin/sh
#Script Name: ScriptParam.sh
#Purpose: Script parameters demo
echo "There are $# parameters"
echo "The parameters are $@"
echo "The script name is $0"
echo "The first parameter is $1"
echo "The second parameter is $2"
exit 0

OutPut: /.ScriptParam.sh reni sam
             There are 2 parameters
             The parameters are reni sam
             The script name is ./ScriptParam.sh
             The first parameter is reni
            The second parameter is sam

Assignments-4


Write a shell script to delete file1.txt & to give RWX permissions to all users on file2.txt. Take file1.txt and file2.txt as shell script parameters. (3 Min)

If-then-fi

Syntax: if [ condition ]
             then
                Statements
            fi

Example:

#! /bin/sh
#Scriptname: ifthenfi.sh
#purpose: To demonstrate if-then-fi
echo "Is it morning? Please answer yes(1) or no(0)"
read response
if [ $response -eq 1 ]
    then
         echo “good morning”
fi
exit 0

if-then-else-if

Syntax: if [ condition ]
             then
                 Statements
            else
                Statements
            fi

Example:
#! /bin/sh
#ScriptName: Ifthenelsefi.sh
#purpose: To demonstrate if-then-else-fi
if [ -d /home/faculty ]
then
    echo “/home/faculty is a directory”
else
    echo “/home/faculty is not a directory”
fi
exit 0

Assignments-5

Write a shell script to check whether read number is even or odd? (Time: 2 Min)
Write a shell script to check given file(take this a script parameter) is plain file or directory. (Time: 2 Min)


Case Statement
Syntax:
case variable in
Pattern ) statements ;;
Pattern ) statements ;;
......
esac

Example:
#! /bin/sh
#ScriptName: Case.sh
#purpose: To demonstrate case statement
echo “is it morning? Please anser yes or no”
read timeofday
case “$timeofday” in
yes | Y | y | YES ) echo “Hi”
echo “good morning” ;;
yo | N | n | NO ) echo “Hi”
echo “Good After Noon” ;;
* ) echo “sorry answer not recognized” ;;
esac
exit 0


For Loop

Syntax: for variable in values
            do
                Statements
           done
Example:
#! /bin/sh
#ScriptName: For.sh
#Purpose: To demonstrate for loop
for file in $(ls *.sh)
do
     echo “$file”
done
exit 0

Note: You can use loop controls break, continue in for loop with a value.

While loop
Syntax: while [ condition ]
             do
                 Statements
            done

Example:
#! /bin/sh
#ScriptName: While.sh
#Purpose: To demonstrate While loop
echo "enter password:"
read password
while [ "$password" != "secret" ]
do
    echo "try again"
    read password
done
exit 0

Note: You can use loop controls break, continue in while loop with a value.
Note: Explore do-while loop for yourself

Arrays in Shell Script

An array variable can hold multiple values at the same time and each value can access using index value.

Example:

#!/bin/sh
#ScriptName: Array.sh
#Purpose: To demonstrate Array in shell script
name[0]="Reni"
name[1]="Sam"
name[2]="Ashok"
name[3]="Mahesh"
#Displaying array item based on index number
echo "First Method: ${name[0]}"
echo "First Method: ${name[2]}"
# Different method to display all items in array
echo "First Method: ${name[*]}"
echo "Second Method: ${name[@]}"
exit 0
 
Function with No parameters & No return 
#!/bin/sh 
#ScriptName:Function1.sh 
#Purpose: To demonstrate function with no #parameters & no return 
# Function Hi definition 
Hipgdst () { 
   echo "Hi PGDST" 
} 
# Invoking function Hi 
Hipgdst 
exit 0

Function with  Parameters & Return Value
#!/bin/sh
#ScriptName:Function2.sh
#Purpose: To demonstrate function with parameters & return val
# Function add definition
add () {
   return `expr $1 + $2`
}
# Reading 2 nums for adding through func
echo "enter first number"
read a
echo "enter second number"
read b

# Invoking function add with a & b as #parameters
add $a $b
# Capture value returned by last command
sumval=$?
echo "Return value is $sumval"
exit 0


Shell Script Assignments
  1. Write a shell script to check read number is prime or not? (use for / while loop) 
  2. Write a shell script to determine whether the given word begins with lower case 
    or upper-case letter or whether it is starting with a special character using case statement. (use case) 
  3. Write a shell script to read contents of a file (which has been provided 
    as a script parameter) line by line and display on screen. (use while loop) 
  4. Write a shell script to read 10 values into an array and print them on screen using array index. 
  5. Write a shell script to read 5 values into array1 and 5 values into array2 and concatenate 
    both arrays store in array3. 
  6.  Write shell script functions to calculate +, -, *, / , % of two numbers which 
    are provided as parameters to the functions and and each function must return result. 
    Call all those functions and print return values. 
  7. Write a single shell script to do the following
    a. Create a file profile.txt 
    b. Change permissions of profile.txt to _rwxr_xr_x 
    c. Read your name, e-mail id, roll number and write them to profile.txt 
    d. Read the contents of profile.txt using a loop and display on screen. 
  8. Write a single shell script to do the following
    a. read a number 
    b. Define a function checkprime() which takes read number as parameter 
    & checks that number is prime or not & return the result. 
    c. Call checkprime() with parameters 12, 97, 111
    d. Display the return values of above function calls on screen 
  9. Write a single shell script to 
    a. read a number N 
    b. read N numbers in to an array called array_all using loop 
    c. Navigate through array_all and check for even & odd numbers. Store 
    all even numbers in array even_array & odd numbers in array odd_array 
    d. display all even numbers then odd numbers on screen.