Shell Scripts: Unit 4 Essential Shell Programming
Shell Scripts: Unit 4 Essential Shell Programming
SHELL SCRIPTS
When a group of commands have to be executed regularly ,they should be stored
in a file ,and the file itself executable as a shell script or shell program. Though it’s not mandatory
,we normally use the .sh extension for shell scripts , this makes it easy to match then with wild –
cards.
Shell scripts are executed in a separate child shell process ,and this sub-shell need not
be of the same type as your login shell. In other words ,even if your login shell is Bourne ,you can
use a Korn sub-shell to run your script. By default ,the child and parent shells belong to the same
type ,but you can provide a special interpreter line in the first line of the script to specify a different
shell your script.
For e.g.
$ bash first
$ /bin/sh first
Note that to run script, you need to have in same directory where you created your script, if
you are in different directory your script will not run (because of path settings), For eg. Your home
directory is ( use $ pwd to see current working directory) /home/vivek. Then you created one script
called 'first', after creation of this script you moved to some other directory lets
say/home/vivek/Letters/Personal
, Now if you try to execute your script it will not run, since script 'first' is in /home/vivek directory,
to Overcome this problem there are two ways First, specify complete path of your script when ever
you want to run it from other directories like giving following command
$ /bin/sh /home/vivek/first
#!/bin /bash/sh
Script.sh
output:
chmod +x script.sh
./script.sh
February 2019
Su Mo Tu We Th Fr Sa
2 3 4 5 67 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
My shell:/bin/sh
STATEMENTS:
Read: The read statement is the shells internal tool for taking input from the user , i.e making
scripts interactive .It is used with one or more variables .Input supplied through the standard input is
read into these variables .when you use a statement like
read name
the script pauses at the point to take input from the keyboard. Whatever you enter is stored in the
variable name .since this is a form of assignment ,no $ is used before name.The script ,emp1.sh uses
read to take a search string and filename from the terminal .
#!/bin/sh
echo “Enter the pattern to be searched : \c”
read pname
echo “Enter the file to be searched to be used : \c”
read flname
echo “searching for $pname from file $flname”
grep “$pname” $flname
grep “selected records shown above”
$emp1.sh
Enter the pattern to be searched :director
Enter the file to be searched to be used :emp.lst
Searching for director from file emp.lst
9876|jai sharma|director|production|12/3/2019|7000
2365|varun sengupta|director|personnel|11/2/2018|7800
selected records shown above
The scripts first asks for a pattern to be entered .Input the string director,which is
assigned to the variable pname. Next, the script asks for the filename ;enter the string emp.lst, which
is assigned to the variable flname.grep the runs with these two variables as arguments.
A single read statemen can be used with one or more variables to let you enter multiple
arguments :
If the number of arguments supplied is less than the number of variables accepting them ,any
leftover variables will simply remain unassigned .
Test: test can be used to test the various file attributes like its type (file,directory or symbolic
link)or its permissions (read,write,execute)Both perl and UNIX system call library also offer these
facilities.
$ls –l emp.lst
0 yes
1 No
The ! negates a test,so [ ! –w foo ] negates [ -w foo ] .Using these features you can design a script
,filetest.sh,that accepts the file name as argument and then performs a number of test on it.Test the
script with two filenames-one that doesn’t exist and one that does :
$filetest.sh emp3.lst
$filetest.sh emp.lst
This completes the discussion on the three domain of test –numeric comparison ,testing of strings
and file attributes .even though we used test with the if statement in all of our examples,test returns
an exit status only ,and can thus be used with any shell construct that uses an exit status.test also
finds wide application in the while statements.
$vi filetest.sh
#!/bin/sh
If [ !-e $1 ] ; then
elif [ ! –r $1 ] ; then
elif [ ! –w $1 ] ; then
else
fi
If case: The case statement is the second conditional offered by the shell .It doesn’t have a
parallel either in C (switch is similar) or perl. The statement matches an expression for more than
one alternative, and uses a compact construct to permit multi way branching. case also handles string
tests ,but in a more efficient manner than if. The general syntax of the case statement is as follows :
case expression in
pattern1)commands1 ;;
pattern2) commands2 ;;
pattern3) commands3 ;;
esac
Example :
#!/bin/sh
read choice
case “$choice” in
1) ls –l ;;
2) ps –f ;;
3) date ;;
4) who ;;
5) exit ;;
*)echo “Invalid option ’’
esac
$ menu.sh
1. List of files
2. proc;esses of user
3. Today’s Date
4. Users of system
5. Quit to Unix
Enter your option :3
Tue Jan 7 18:03:06 IST 2019
computation :
expr can perform the four basic arithmetic operations as well as the modulus
(remainder)function:
$ expr 3 + 5
$ expr $x - $y
-2
15
$ expr $y / $x
$ expr 13 % 5
The operand ,be It +, -, * etc , must be enclosed on either side by whitespace.observe that
multiplication operand(*) has to be escaped to prevent the shell from interpreting it as the filename
metacharacter . since expr can handle only integers ,division yields only the integral part.expr is
often used with command substitution to assign a variable .For example ,you can set a variable z to
the sum of two numbers :
$ x=6 y=2 ; z=`expr $x + $y`
$echo $z
LOOPS:
While Loop: The while loop enables you to execute a set of commands repeatedly until some
condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
None of the pattern scanning scripts developed so far offers the user another chance to rectify a
faulty response. Loops let you perform a set of instructions repeatedly.
Syntax:
do
commands
done
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
output:
4
5
Each time this loop executes, the variable a is checked to see whether it has a value that is less than
10. If the value of a is less than 10, this test condition has an exit status of 0. In this case, the current
value of a is displayed and later a is incremented by 1.
For loop: The shell’s for loop differs in structure from the ones used in other programming
languages.There is no three-part structure as used in C,awk and perl.Unlike while and until ,for
doesn’t test a condition ,but uses a list instead:
Syntax
do
done
Example:
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
Output:
0
1
2
3
4
5
Until loop: It is similar to while loop. The only difference is that until statement executes its code block
while its conditional expression is false, and while statement executes its code block while its conditional
expression is true.
Syntax:
until [ condition ]
do
command1
command2
...
....
commandN
done
Example:
#!/bin/bash
i=5
until [ $i –gt 15 ];
do
i=$(( i+1 ))
done
Output:
Number 5
Number 6
Number 7
Number 8
Number 9
Number10
Number 11
Number 12
Number 13
Number 14
Number 15
$_
This assigns the value 9876 to the positional parameter $1 ,2345 to $2 and 6213 to $3.It also
sets the other parameters $# and $*.
This features is useful when used with commands that don’t accept a filename as
argument (like the mailx command ,for instance). If the message is short (which any mail
message is normally expected to be),You can have both command and message is normally
expected to be ),You can have both the command and message in the same script:
Mailx sharma << MARK
Your program for printing the invoices has been executed
On `date`, check the print queue (command substitution permitted)
The updated file is known as $flename ( variable evaluation too)
MARK (Nospaces permitted here)
The here document symbol(<<) is followed by three lines of data and a delimiter (the
string MARK).The shell treats every line following command and delimited by Mark as input
to the command .sharma at the other end will see the three lines of message text with the date
inserted by command substitution and the evaluated filename.
The word MARK itself doesn’t show up. When this sequence is placed inside a script,
execution is faster because mailx doesn’t have to read an external file; it’s here.
EXIT STATUS OF A COMMAND
Every Linux command executed by the shell script or user, has an exit status.
The exit status is an integer number.
The Linux man pages stats the exit statuses of each command.
0 exit status means the command was successful without any errors.
A non-zero (1-255 values) exit status means command was failure
echo $?
date # run date command
echo $? # print exit status
foobar123 # not a valid command
echo $? # print exit status
$? reads the exit status of the last command executed. After a function returns, $? gives
the exit status of the last command executed in the function.
This is Bash's way of giving functions a "return value." [1] Following the execution of a
pipe, a $? gives the exit status of the last command executed. After a script terminates, a $? from the
command-line gives the exit status of the script, that is, the last command executed in the script,
which is, by convention, 0 on success or an integer in the range 1 - 255 on error.