Professional Documents
Culture Documents
Shell Variables –
The variable is a value that can be changed according to the requirement of user.
•User created shell variables- we can type name of variable with value
e.g. $ n=0 etc.
2. Standard shell variable or System shell variable - the shell maintains its own set of shell
variables. Some times they are called as keyword variables. Most of the keyword variables
are either inherited by the shell when it is started up. You can assign new values to these
variables from the command line or from the .profile file in your home directory.
these variables can be see through – set command
$ set
SHELL PROGRAMMING
There are three king of construct in any programming language
•Sequential
•Conditional
•Iterative
•Sequential – where each statement execute sequentially i.e. each statement depends on the
previous statement.
e.g. write a shell script to calculate sum of two no.s
Integer Arithmetic
there are following commands which are used for Integer arithmetics –
Conditional Constructs –
If then else –
If [ condition ]
then
------
else
---------
fi
e.g. write a shell script to find max among 2 nos.
echo “enter 2 nos:”
read a
read b
If [ $a –gt $b]
then
echo “$a is greater”
else
echo “$b is greater”
fi
Switch case –
case $variable
•statement1 ;;
•Statement2 ;;
•Statement3 ;;
•--------
esac
e.g. Write a Shell script to enter choice if choice is + then add 2 nos, - then subtarct etc.
echo “enter 2 nos :”
read a
read b
echo “enter choice : + - * or /”
read ch
case $ch
‘+’) c=`expr $a + $b`
echo $c ;;
‘-’) c=`expr $a - $b`
echo $c;;
esac
-f ordinary file
-d Directory file
•write a shell script to check whether a particular file has read permission or not if not then assign
read permission.
Assignment
3. Iterative Constructs – are the programming techniques where a particular operations needs
to repeat several time to find a particular result.
e.g. echo "Total number of command line argument are in e.g. 1 $# $@"
echo "$0 is script name"
echo "$1 is first argument"
echo "$2 is second argument"
echo "All of them are :- $* or $@"
$# - 3, $0 – myfile, $1 – foo , $2 – bar , $@=3
Problems –
•Write a shell script with the help of command line arguments to check whether no. is even or
odd.
Vi even
C=`expr $1 \% 2`
If [ $c = 0 ]
then
echo “no is even”
Else
echo “no is odd”
Fi
2. Write a shell script using command line arguments to check whether no. is prime or not.
3. Calculate factorial of a no.
for loop –
for <var> in <range>
do
------------
done
e.g. for I in 1 2 3 4 5
do
echo $i
done
1. Write a shell script to check whether following patterns are in data file or not.
Vi file
for j in $* # $* = is that ok
do
grep “$j” data
done
String Handling –
a=“bombay”
c=`expr “$a” : ‘.*’`
echo $c # will display 6
a=“bombay”
c=`expr “$a” : ‘..\(..\)’`
echo $c # will display “mbay”