Académique Documents
Professionnel Documents
Culture Documents
Version 1.0
January, 2013
Sahil Dhuria
sahil.dhuria@tcs.com
Notice
Document details
Name
Basics of UNIX SHELL SCRIPTING
Version no.
1.0
Description
This document is intended for beginners in UNIX
shell scripting.
Revision details
Action taken
(add/del/change)
Previous
page no.
Revision description
Approved by:
Authorised by:
Date:
Date:
TCS Public
Pre-Requisite
Qualifications Criteria
TCS Public
CONTENTS
BASICS OF SHELL SCRIPTING - INTRODUCTION ............................................................................................. 4
READ STATEMENT .......................................................................................................................................... 5
COMMAND LINE ARGUMENTS ...................................................................................................................... 6
USE OF && AND || LOGICAL OPERATORS .................................................................................................... 8
CONTROL CONSTRUCTS ................................................................................................................................. 9
COMPUTATIONS USING EXPR ..................................................................................................................... 16
SET AND SHIFT : MANIPULATION OF POSITIONAL PARAMETERS .............................................................. 17
DEBUGGING SHELL SCRIPTS USING SET -X ............................................................................................... 18
EXAMPLE : SCRIPT FOR MAKING A BASIC CALCULATOR ............................................................................ 20
TCS Public
(interpreter line)
(comment starting from #)
To execute it we just need to write script name with shon the command prompt as:
$ sh samplescript.sh
Here it is to be noted that the comments always start with # sign except for the first line
where it is used with ! sign as an interpreter line. The interpreter line above tell the system
that in what shell a user wants to execute his script. Here sh indicates a bourne shell.
One thing to be noted here is that if you dont have the execute permissions for the file you
wont be able to execute the script. So you have to change the permissions of the file as
mentioned below:
$ chmod +x samplescript.sh
TCS Public
read STATEMENT
The sample script written above dont ask for any input from the user when we execute this.
In some cases like when a script performs calculations, it will ask for some input from the
user on which it will perform calculations. For such cases read statement is used in the
script. In other words, a read statement is used to make a script interactive.
Here is the example of usage of read :
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------The code above will display the lines of file flname containing the word pname.
Output:
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------You can use a single read statement to enter multiple arguments as:
read pname flname
But if the number of arguments entered by the user are more than the number of
arguments mentioned in the command line then the extra arguments will be assigned to the
last variable mentioned in the command line. On the contrary if they are less than the
number of mentioned variable then the leftover variables will remain unassigned.
TCS Public
--------------------------------------------------------------------------------------------------------------------------To run the above script a user will write command like this:
$ sh demo1.sh sahildhuria employees.txt
Output:
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------You can clearly see that the arguments mentioned in the command line are stored in the
positional parameters $1,$2 respectively.
TCS Public
exit
To see whether a command has run successfully or not we can use a shell parameter $?.
The value returned by this parameter tell the user whether the command has been run
successfully or not.
Lets check this out:
------------------------------------------------------------------------------------------------------------------------
TCS Public
or
Command
The command will be executed in a sub-shell environment and the standard output of the
shell will replace the command substitution when the command completes.
TCS Public
Control Constructs
The flow of control within shell script is done via four main constructs viz.;
if...then...elif..else, do...while, for and case. These are discussed one by one as below:
The if CONDITIONAL
The generic forms of this control construct is as:
Form1
Form2
if command is successful
then
execute this command
else
execute this command
fi
if command is successful
then
execute this command
fi
Form3
if command is successful
then
execute this command
elif command is successful
then
execute this command
else
execute this command
fi
A few things that should be always keep in mind while using if construct are:
Example:---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------Output:
---------------------------------------------------------------------------------------------------------------------------
TCS Public
--------------------------------------------------------------------------------------------------------------------------As we know grep will return an exit status, the if construct use this exit status to proceed
further in the code block. In the above code if the returned status is 0,means grep executed
successfully. And then Pattern found will be displayed. If the returned status is other than
0 then Pattern not found will be displayed.
Use of test and []
In case of expressions if cant handle the true or false status returned by expressions.
Because if decides flow of execution on the basis of numerical (0 or 1) exit status of the
command. But in the case of expressions exit status is returned as either true or false. So
here test statement comes in operation. A test statement evaluates the expression and
returns 0 or 1 on the basis of true or false returned by the expression. test actually doesnt
display 0 or 1 after evaluation, but is sets a parameter $?. In the following example we will
see this.
Example:
$ set x=1; y=3 ; z=5
$ test $x eq $y ; echo $?
1 (means the result was false and these are not equal)
$ test $x -lt
$y ; echo $?
The numerical operators used for comparison are different from those used in other
languages. Here is the list of operators used by test:
OPERATORS
-eq
-ne
-gt
-ge
-lt
-le
MEANING
Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
LOOPING
Do..While Loop
TCS Public
10
Loops are used to repeat a set of instructions. Previously we rectified a faulty response using
if but there was no provision of doing the same things until a certain condition remains true.
Loops are used for such situations. There are three types of loops: while,until and for.
While loop repeatedly performs a set of commands until the control command returns a
true exit status. The generic syntax is:
While condition is true
do
commands
done
Lets use a while loop along with a test statement,
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------One of the good applications of the while loops is that we can make the system to pause
until certain condition is met. In the following example system goes to sleep (remains
paused) until a.lst file is created and becomes readable. And when it becomes readable it
displays a message,
---------------------------------------------------------------------------------------------------------------------------
TCS Public
11
--------------------------------------------------------------------------------------------------------------------------This program will check after every 30 second if the file a.lst has been created and readable.
If its created and readable then it will display the message The file is created.
Until
It is just reverse of the while loop, means it will execute the body of the loop until the
condition remains false. As soon as the condition becomes true it comes out of the loop.
for loop
The syntax for the for loop is as follows:
for variable in list
do
commands
done
Its different from the while loop in the sense that its executed a specific number of times.
Whereas in while loop it waits for the condition to become false to stop the loop, in for loop
the same applies but with a predefined limitation as shown in the syntax. So, here the
commands get executed until the words from the list gets assigned to variable in turn. It will
be more clear from the following example.
---------------------------------------------------------------------------------------------------------------------------
TCS Public
12
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------for loop is the most commonly used loop in the unix system. The list can consist of different
kind of expressions. For example, list from variables, list from command substitution, list
from wild-cards, list from positional parameters are the few examples. These can be learned
during advanced shell programming.
case conditional
The syntax of the case conditional is:
case expression in
pattern1) command1 ;;
pattern2) command2 ;;
pattern3) command3 ;;
..
Esac
case first matches the expression with pattern1. If the match is found then it executes
command1, if not then it continues in same manner to fine the match. Each command list is
terminated with a pair of semicolons except for the last command list where its optional.
Lets demonstrate case conditional with an example.
TCS Public
13
---------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
TCS Public
14
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------Here if the user has entered n or N or anything else, the program will be stopped and control
will be returned to the prompt. Even if the user has entered y or Y. the same will happen but
with a little delay that is not noticeable here. You can check the script by echoing something
like your name then the script will exit but after displaying your name on the screen.
TCS Public
15
--------------------------------------------------------------------------------------------------------------------------The operators should have whitespace on both of their side. expr also be used to assign a
value to a variable as:
$x = 5
$x = expr $x + 1
$ echo $x
Anwer is 6.
TCS Public
16
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------shift command is used to shift the positional parameters to one position left. It will be more
clear after the following example.
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
TCS Public
17
---------------------------------------------------------------------------------------------------------------------------
TCS Public
18
--------------------------------------------------------------------------------------------------------------------------Using set +x
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------This is an ideal tool to use if you have problems finding why your scripts dont work in the
manner as they are expected.
TCS Public
19
---------------------------------------------------------------------------------------------------------------------------
TCS Public
20
In the above code there is a while loop in which there is a case statement that performs
arithmetic operations based on the users choice. Initially a true condition is set to enter in
the while loop and then inside the loop there is an option whether the user wants to
continue with the more calculations or he wants to exit from the calculator. Based on his
choice further operations are performed. The Output of the above code is displayed as
below:
---------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------TCS Public
21
THANK YOU
TCS Public
22