Saturday, 15 August 2015

Shell Programs

Shell Sample Programs


1. WAS,to display list of files, the current working user‘s list and present working directory
$vi sp1
ls -x
who
pwd


:wq(save and quit)
Execution of shell program:
Sh is the command to execute bourn shell programs

eg: $sh sp1
or
$chmod 744 sp1

$./sp1

2)WAS, to display address

$vi sp2

echo “Multics Scripting Institute”
echo “No:109, 1st floor”
echo “Eurekha court,”
echo “4th floor”
echo “Ameerpet,”
echo “Hyderabad”

:wq(save and quit)

3)WAS, to  count no of users are currently logged into the system

$vi sp3.sh

echo “There are `who |  wc  -l ` users”

:wq(save and quit)

4)WAS, to read name and display

$vi  sp4.sh

echo “what is your name?”
read name
echo “hello $name”

:wq(save and quit)

Note :- read is command to read variable form the user .Read command reads value form keyboard up to space or enter key.
Eg1: read a
Eg 2: read a b--c

5)WAS, to read 2 number and display

Vi sp5

echo “enter 2 numb:\c”
read a b
echo “your numbers are $a and $b

:wq(save and quit)

OPERATORS:

1 .Arithmetic operators
2. Relational operators
             a. Numeric comparison operators
             b. String comparison operators
3. Logical operators


1. Arithmetic Operators
Operator                                                             Meaning
+                                                                             Sum
-                                                                       Difference
*                                                                             Product
/                                                                              Division
%                                                                            Modulus division

2. Numeric comparison operator
Operator                                                             Meaning
-gt                                                                          greater than
-ge                                                                         greater than equal to
-lt                                                                            less than
-le                                                                           less than or equal to
-eq                                                                         equal to
-ne                                                                         not equal to

3. String Comparison Operators
Operator                                                             Meaning
 >                                                                            Greater than
<                                                                             Less than
=                                                                             Equal to
!=                                                                            Not equal to

4.Logical Operators
Operator                                                             Meaning
-a                                                                            Logical AND
-o                                                                            Logical OR
!                                                                              logical NOT

5.Assignment operator                                 =

In UNIX for each and every operator, note that there should be space before and after operators.
If we don’t give space for “=” operator it can be consider as assignment else string comparison operator

6)WAS, to read 2 float numbers and display sum, difference, product and division

$vi sp7
echo “enter 2 float numbers” read a b
c=`echo $a + $b I bc`
 echo “a+b=$c”

7)WAS, to read 2 numbers an d display sum, difference, product and division

visp6

echo “enter 2 numbers”
read a b
c=`expr $a + Sb`
echo “a+b$c”
c=`expr $a - $b`
echo “a-b=$c”
c=`expr $a \* $b`
echo “a*b=$a”
c=`expr $a / $b`
echo “alb=$c”

:wq(save and quit)

Note: expr is the command to evaluating arithmetic expressions. But expr is capable of carring out only integer arithmetic.

....WAS, to read 2 float number and display Sum, difference, product and division

$vi sp7

echo “enter 2 float numbers”
read a b
c=`echo $a+$b | bc`
echo”a+b=$c”
c=`echo.$a - $b | bc`
echo “a-b=$c”
c=`echo $a \* $b bc`
echo “a*b=$a”
c=`echo $a / $b | bc`
echo “alb=$c”

:wq(save and quit)


CONTROL STATEMENTS:

There are four types of control instructions in shell. They-are:

1. Sequence Control Instruction
2. Selection or Decision Control Instructions
3. Repetition or Loop Control Instruction
4. Case Control Instruction

The sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. Decision and case control instructions allows the computer to take a decision as to which instruction is to be executed next. The loop control instruction helps computer to executer group of statements repeatedly.

Decision Control Statement
1. if —then-fl statement
2. if-then-else-if statement
3. if-then-elif-fi statement
4. case-esac statement

1.if-then-fi statement
Syntax:
if control command
…………..
…………
…………..

fi
The if statement of UNIX is concerned with the the exit status of a command. The exit status indicates whether the command was executed successfully or not. The exit status of a command is 0 if it has been executed successfully, 1 otherwise.

8) WAS, to change directory

$vi sp8

echo enter directory name
read  dname
if  cd  $dname
then
echo “changed to $dnarne”
pwd
fi

:wq(save and quit)

2.Jf-then-else-fi Statement
syntax
if condition
then
………
………
else
………
………

fi
The exit status of the control command is 0 then it executes then statement otherwise it executes else statements.


9) WAS, to copy a file

$vi sp9
echo enter source filename and target file and name
read  src  trg
if  cp  $src  $trg
then
echo   file copied successfully
else
echo   failed to copy the file
fi

:wq(save and quit)

10) WAS,  to search string in a file

$vi sp10.sh

echo “enter a file name”
read  fname
echo “enter to string to search”
read str
if  grep $str  $fname
then
echo “$str is found in the file $file”
else
echo “$str is not found in $fname”
fi

:wq(save and quit)

11)WAS, to find greatest number of 2 numbers

vi sp 11
echo enter two numbers
read a b
if  [ $a –gt  $b ]
then
echo $a is the greatest value
else
echo $b is the greatest value

fi

:wq(save and quit)

12) WAS, to check given no is even or odd

$vi sp12

echo enter a number
read n
if [  `expr $n % 2`  -eq  0 ]
then
echo $n is even number
else
echo $n is odd number
fi

:wq(save and quit)

The Test Command

If constructs depends upon whether or not the condition results into true or not.
If constructs are generally used in conjunction with the test command. The test command helps us to find the contents of a variable, the number of variables and the type of file or kind of file permission. The test command returns an exit status after evaluating the condition.

Syntax: -
If test condition
Then
Commands
Else
Commands
fi

13) WAS, to check how many users working on the system

$vi  sp13

total=`who | wc –l`
if  [  $total  -eq  1 ]
then
echo “you are the only user working…
else
echo “there are $total user working…
fi

:wq(save and quit)

14)  WAS,  to check given number is +ve or –ve number

$vi sp14

echo “enter a number”
read num
if  test  $nurn  -gt  0
then
echo “$num is +ve number” else
echo “$num is —ve number”
fi

;wq(save and quit)

15)  WAS, to find student result

4vispl5

echo “enter three subject marks:”
read ml m2 m3
if  [  $ml  -ge  40  ]
then
if  [  $m3 -gt  40 ]
then
if  [  $m3  –gt  40  ]
then
echo “PASS”
else
echo “FAIL”
fi
else
echo “FAIL”
fi
else
echo “FAIL’
fi
:wq(save and qut)

16)WAS, to print greeting

$vi spl6

hour=`date | cut  -c 12,33`

if   [  $hour  —ge   0  —a   $hour  —le   11]
then
echo “Good Morning”
else

if  [  $hour  -ge  12  -a  $hour -Ie 17  ]
then
echo “Good Afternoon”
else
echo “Good Evening”
fi
fi

:wq(save and quit)

File Test Commands
The test command has several options for checking the status of a file.
-e            True if the file exist.
 -s           True if the file exists and has a size greater  than 0
-f             True if the file exists and is not directory
-d            True if the file exists and is a directory file
-c            True if the file exists and character special file
-b            True if the file exists is a block special file
-r             True if the file exists and have a read permission to it
-x            True if the file exists and have a execute permission to it
-w           True if the file exists and have a write permission to it


17) WAS, to  check for ordinary file and display it contents
$vi sp17

echo enter a file name
read fname
if test  -f  $fname
then
cat  $fname
else
echo “given file is not ordinary file”

:wq(save and quit)

18) WAS, to  check give file is ordinary or directory file

$vi sp18

echo “enter a file name:”
read fnarne
if  [ -f  $fname ]
then
cat  $fname
elif  [  -d  $fname   ]
then
ls
else
echo $fname is not file and not a directory
fi

:wq(save and quit)

19) WAS, to check read permission

$vi sp19

echo “enter a file name
read  fname
if  [  -r  $fname  ]
then
cat  $fname
else
chmod  u+r  $fname
cat  $fname
fi

:wq(save and quit)

20) WAS, to append data to the file

$vi sp20

echo “enter a filename”
read  $fname
if  [  -f  $fname  ]
then
if [  -w   $fname  ]
then
echo “enter data to file to stop press ctrl+d...”
cat  >>$fnarne
else
chmod  u+w   $fname
echo “enter data to file to stop press ctrl+d…”
cat  >>$fname
fi
else
echo “enter data to file to stop press ctrl+d…”
cat  >>$fname

fi
:wq(save and quit)

String Test Commands

Condition                            Meaning
String 1 = string2               True if the strings are same
Stringi != string2               True if the strings are different
-n string 1                            True if the length of string is greater than 0
-z string                                True if the length of the string is zero

21) WAS, to compare two strings

$vi  sp21.sh

echo “enter first string:”
read str1
echo “enter second string:”
read str2
if test $str1  =  $str2
then
echo “both strings are equal”
else
echo “strings are not equal”
fi

:wq(save and quit)

22) WAS, to check given string is empty or not

$vi sp22

echo enter a string
read str
if  [  -z  $str  ]
then
echo “string is empty”
else
echo ‘given string is not empty”
fi

:wq(save and quit)


Case Control Statement

Syntax -
Case value in
Choicel)
…………..
…………..
‘’
‘’

cho ice2)
………
………
‘’
‘’
choice3)
………
………
‘’
‘’
esac

Firstly, the expression following the case keyword is evaluated. The value that it yields is then matched, one by one against the potential choices (choice1, choice2 and choice3 in the above form). When a match is found, the shell executes all commands in that case up to;;. This pair of semicolons placed at the end of each choice is necessary.

23)Sarnple program for case

$vi sp23

echo “enter a number between 1 to 4”\c”
read num
case $nurn in
1)echo “you entered 1” ;;

2)echo “you entered 2” ;;

3)echo “you entered 3” ;;

4)echo “you entered 4” ;;

*)echo “invalid number, enter number between 1to4 only” ;;

esac

:wq(save and quit)

24) WAS, to check given character is upper case alphabet or lower case alphabet or digit or special character

$vi sp24

echo “enter a single character”
read ch
case  $ch  in
[a-z])echo   “you entered a small case alphabet” ;;

[A-Z])echo   “you entered a upper case alphabet” ;;

[0-9])echo  “you entered a digit” ;;

?)echo  “you entered a special character”;;


*)echo “you entered more than one character”;;

esac
:wq(save and quit)

25)WAS, to display file conten ts or write on to file or execute based on user choice

$vi sp25

echo “enter a file name:\c”
read   fname
echo            “Main Menu”
echo  “======================”
echo  “r. read mode”
echo  “w.write mode”
echo   “x. execute mode”
echo   “enter mode:\c”
read  mode
case  $mode  in
r)
if  [ -f $fname  -a   -r  $fname  ]
then
cat  $fname
fi
;;
w)
if  [ -f  $fname   -a   -w  $fname  ]
then
echo “enter data to file at end press ctrl+d:”
cat   >$fname
fi
;;
x)
if  [  -f  $fname   -a  -x  $fname  ]
then
chmod  u+x  $fname
$fname
fi
;;
*)echo  ”you entered invalid mode…”
;;

esac


:wq(save and quit)

Looping Control Statements
A loop involves repeating some portion of the program either a specified no of times of times or until a particular condition is being satisfied. There are three methods by way of which we can repeat a part of a program. There are

1) Using a while statement
2) Using a until statement’
3) Using a for statement


While Statement
Syntax

while [condition j
do
……………
……………
……………
done

The statements within the while loop would keep on getting executed till the condition is true. When the condition is false, the control transfers to after done statement.

27) WAS, to display numbers 1 to 10

$visp27

echo “the number form 1 to 10 are:”
i=1
while  [  $i  -Ie  10 ]
do
echo  $i
i=`expr  $i  +  1`
done

:wq(save and quit)


28) WAS, to copy file from root to user directory

$vi sp28

flag=1
while  [  $flag   -eq   1  ]
do
echo “enter a filename”
read  fname
cp  $fname    /usr/sv/$fname
echo “$fname copied………..”
echo “do u wish to continue [1 -yes/0-no]:  ”
read flag
done


:wq(save and quit)

The Break Statement
When the keyword break is encountered inside any loop, control automatically passes to the first statement after the loop.
The Continue Statement
When the keyword continues is encountered inside any loop, control automatically passes to the beginning of the loop.
29)WAS, to display file contents if file existing

$vi sp29
x0
while  test  $x=0
do
echo “enter a file name:\c”
read  fname
if   test  ! –f  $fname
then
echo “$fname is not found………..”
continue
else
break
fi
done
cat $fnarne | more

:wq(save and quit)

The Until Loop
Syntax
until [condition j
do
……………
……………
……………
done

The statements within the until loop keep on getting executed till the condition is false. When the condition is true the control transfers to after done statement.

30) WAS, to print numbers 1 to 10

$vi sp3O

i=1
until  [  $i  -gt  10  ]
do
echo  $i
i=`expr$i+1`
done

:wq(save and quit)

The True and False Command
To execute the loop an infinite no of times.

31) Write sample program for true command

$vi sp3l

while true
do
clear
banner “hello”
sleep 1
clear
banner “Tecnosoft”
sleep 1
done

:wq(save and quit)

Note: The above program executes continuous to stop execution press ctrl + break

32) Write sample program for false command

$vi sp32

until  false
do
clear
banner “hello”
sleep 1
clear
banner “Tecnosoft”
sleep 1
done

:wq(save and quit)
The Sleep Command
The sleep command stops the execution of the program the specified no of seconds.

The For Loop
Syntax

For variable in va1ue1value2 value3 . ... . value
do
………………….
……………….
done
The for allows us to specify a list of values which the variable in the loop can take. The loop is then executed for each value mentioned in the list.

33) WAS, to demonstrate for loop

$vi sp33

for i in 1 2 3 4 5
do
echo $i
done

:wq(save and quit)

34) WAS, to demonstrate for loop

$vi sp34

for  i  in Multics is a training institute.
do
echo $i
done

:wq

35) WAS,to display all files in current directory

$vi sp35

for  i in *
do
if  test   -f  $i   -a   -r  $i
then
cat $i |more
sleep 1
clear
fi
done

:wq(save and quit)

36)WAS, to display all sub-directories in the current directory

$vi sp36

for I in*
do
if [  -d  $i  ]
then
echo $i
fi
done

:wq(save and quit)

Positional Parameters
When the arguments are passed with the command line, shell puts each word on the command line into special variables. For this, the shell uses something called as “positional parameters;. These can be thought of as variables defined by the shell, They are nine in number, named $1 through $9.

Consider the following statement, where sp37 is any executable shell script file and the remaining are the arguments
$sp37 Multics is a computer training and development institute

On entering such command, each word is automatically stored serially in the positional parameters. $1 through $9

37) write program to copy a file using positional parameters

vi sp37

if  cp  $1  $2 -
then
echo “file copied successfully”
else
echo “failed to copy”
fi

:wq(save and quit)

$chmod 744 sp37

$sp37 al a2
in above command it passes al to $1 and a2 into $2, then it copies al
contents to a2.

Special Characters
$*, $@                   Contains entire string of arguments

$# -                        Contains the no for argument specified in the command

$?                           Holds the value of exit status of the previous command

$$                           Holds user parent id




No comments:

Post a Comment