Lab 05 and 06 Shell Scripting
Lab 05 and 06 Shell Scripting
Shell scripting
To suggest more improvements and corrections please feel free to email to [email protected]. All rights are
reserved by the author. Manufactured in Pakistan. Except as permitted under the Pakistan States Copyright Act of 1971,
no part of this report may be reproduced or distributed in any form or by any means, or stored in a database or retrieval
system, without the prior written consent of the author ([email protected]) including, but not limited to, network
or other electronic storage or transmission, or broadcast for distance learning.
8 W R IT E AND E XEC UTE S HELL S C R IPT
Use any editor (gedit etc) to write shell script. Then save the shell script to a directory
and name it intro. Shell scripts don’t need a special file extension, so leave the extension
blank (or you can add the extension .sh).
Every Linux file has a set of permissions that determine whether you can read, write, or
run the file. Running ls -l displays the permissions. The file’s mode represents the file’s
permissions and some extra information. There are four parts to the mode, as illustrated
in
The first character of the mode is the file type. A dash (-) in this position, as in the
example, denotes a regular file, meaning that there’s nothing special about the file. This is
by far the most common kind of file. Directories are also common and are indicated by a
d in the file type slot. The rest of a file’s mode contains the permissions, which break
down into three sets: user, group, and other, in that order. For example, the rw-characters
in the example are the user permissions, the r– characters that follow are the group
permissions, and the final r– characters are the other permissions.
The user permissions (the first set) pertain to the user who owns the file. The second set,
group permissions, are for the file’s group (somegroup in the example). Any user
in that group can take advantage of these permissions. Everyone else on the system has
access according to the third set, the other permissions.
M O D IF Y IN G P E R M IS S I O N S
To execute a script first we will make it executable. To change permissions, use the
chmod command. Only the owner of a file can change the permissions. There are two
ways to write the chmod command:
1. chmod {a,u,g,o}{+,-}{r,w,x}
{all, user, group, or other}, {read, write, and execute} ’+’ means add permission
and ’-’ means remove permission.
For example, to add group (g) and others (o) read (r) permissions to file, you could
run these two commands:
2. chmod h3DigitNumberi
Every digit sets permission for the owner(user), group and others as shown in
Table 2. To set the permission decipher the number first and then execute the
command as
R UNN IN G S HELL S C R IP TS
./script-name
9 I M P O RTAN T P O INT S
9
2. Whenever a semicolon (;) is placed between two commands, shell will treat them
as separate commands. So if you want to write all the commands in your shell
script in one line place a semicolon in between them.
3. A script may start with the line #!/bin/bash to tell your interactive shell that the
program which follows should be executed by bash.
10 VA RIAB L E S I N S HE LL
3. Parametric variables
The shell can store temporary variables, called shell variables, containing the values
of text strings. Shell variables are very useful for keeping track of values in scripts. To
assign a value to a shell variable, use the equal sign (=). Here’s a simple example:
$ STUFF=blah
The preceding example sets the value of the variable named STUFF to blah. To access
this variable, use
2. Don’t put spaces on either side of the equal sign when assigning value to variable.
var=
var=""
10
# ! / b i n / bash
#
# vari abl es i n sh el l s c r i p t
#
myvar= H ell o
echo $myvar
myvar= " Yes dear "
echo $myvar
myvar=7+5
echo $myvar
Notice in last assignment, myvar is assigned the string "7+5" and not the result i.e 12.
S Y S T EM OR E N V IR O N M E NT VA RIAB L E S
An environment variable is like a shell variable, but it’s not specific to the shell. All
processes on Unix systems have environment variable storage. The main difference be-
tween environment and shell variables is that the operating system passes all of your
shell’s environment variables to programs that the shell runs, whereas shell variables
cannot be accessed in the commands that you run. Assign an environment variable
with the shell’s export command. For example, if you’d like to make the $STUFF shell
variable into an environment variable, use the following:
$ STUFF=blah
$ export STUFF
Environment variables are useful because many programs read them for configuration
and options. Listed below are some common environment variables:
1. $PATH
PATH is a special environment variable that contains the command path (or path
for short). A command path is a list of system directories that the shell searches
when trying to locate a command. For example, when you run ls, the shell
searches the directories listed in PATH for the ls program. If programs with the
same name appear in several directories in the path, the shell runs the first match-
ing program. If you run
$ echo $PATH
you’ll see that the path components are separated by colons (:). For example:
$ echo $PATH
Or you can append a directory name to the end of the PATH variable, causing the
shell to look in dir last:
$ PATH=$PATH:dir
2. $HOME
The home directory of the current user.
3. $IFS
An input field separator; a list of characters that are used to separate words when
the shell is reading input, usually space, tab and newline characters.
PA R A M E T R I C VA R IAB LE S
These variables keep the values of the command line arguments passed to the Scripts.
Most shell scripts understand command-line parameters and interact with the com-
mands that they run. These parametric variable passed to the script make the code
more flexible. These variables are like any other shell variable like Environment and
Shell Variables, except that you cannot change the values of certain ones. Following are
some parametric variables and a set of environment variables used to handle paramet-
ric variables.
Try running the script as follows to see how it prints the arguments:
The built-in shell command shift can be used with argument variables to remove
the first argument ($1) and advance the rest of the arguments forward. Specif-
ically, $2 becomes $1, $3 becomes $2, and so on. For example, assume that the
name of the following script is shiftex:
# ! / b i n / bash
echo Argument : $1
s hi f t
echo Argument : $1
s hi f t
echo Argument : $1
Run it like this to see it work:
$ ./shiftex one two three
Argument: one
Argument: two
Argument: three
As you can see, shiftex prints all three arguments by printing the first, shifting the
remaining arguments,and repeating.
The shell maintains a variable called $# that contains the number of items on the
command line in addition to the name of the command ($0).
# ! / b i n / bash
i f [ $ # g t 0 ] ; then
echo " Your command l i n e c o n t a i n s $ # arguments "
echo " A l l arguments d is p la y e d u si n g \ $ p o s i t i o n a l parameter "
e ls e
echo " Your command l i n e c o n t a i n s no arguments "
fi
2. Number of Arguments: $#
The $# variable holds the number of arguments passed to a script and is especially
important when running shift in a loop to pick through arguments. When $# is 0,
no arguments remain, so $1 is empty.
3. Script Name: $0
The $0 variable holds the name of the script, and it is useful for generating diag-
nostic messages. For example, say your script needs to report an invalid argument
that is stored in the $errormsg variable. You can print the diagnostic message with
the following line so that the script name appears in the error message:
4. Process ID: $$
The $$ variable holds the process ID of the shell.
11 I N P U T VALU ES
# ! / b i n / bash
#
# S c r i p t to read your name from key board
#
echo " Your f i r s t name p l e a s e : "
read fname
echo " H e l l o $fname , L e t s be f r i e n d ! "
# ! / b i n / bash
#
# S c r i p t to read your name from key board
#
read f i r s t middle l a s t
echo " H e l l o $ f i r s t $middle $ l a s t "
T E ST IN G C O ND IT IO N
test command or [ expr ]
are used to see if an expression is true, and if it is true it return zero(0) otherwise returns
nonzero for false.
The folowing script determine whether given number is equal to 100 or not.
# ! / b i n / bash
#
# S c r i p t to
see whether
argum ent i s
positive
coun t =100
i f [ $count eq 100 ]
then
echo " Count i s 100 "
fi
The folowing script determine whether given argument number is positive using test.
# ! / b i n / bash
#
# S c r i p t to see whether argum ent i s p o s i t i v e
i f t e s t $1 g t 0
then
echo " $1 number i s p o s i t i v e "
fi
1. Mathematical Operators
Figure 2 shows different conditions that we can use to test our expressions. It’s
important to recognize that the equal sign (=) looks for string equality, not nu-
meric equality. Therefore, [ 1 = 1 ] returns 0 (true), but [ 01 = 1 ] returns false.
When working with numbers, use -eq instead of the equal sign: [ 01 -eq 1 ] re-
turns true.
2. String comparisons
Following script checks whether the script’s first argument is "hi" where a string
comparison is made.
# ! / b i n / bash
#
i f [ $1 = h i ] ; then
echo " The f i r s t argument was h i "
fi
There is a slight problem with the condition in preceding example due to a very
common mistake: $1 could be empty, because the user might not enter a parame-
ter. Without a parameter, the test reads [ = hi ], and the command aborts with an
error. You can fix this by enclosing the parameter in quotes::
if [ "$1" = hi ]; then
Operator Meaning
string1 = string2 string1 is equal to string2
string1 != string2 string1 is NOT equal to string2
-n string1 string1 is NOT NULL and does exist
-z string1 string1 is NULL and does exist
s t r i n g 1 =$1
i f [ z " $ s t r i n g 1 " ] ; then
echo "NULL STRING"
fi
i f [ n " $ s t r i n g 1 " ] ; then
echo "NOT NULL STRING"
fi
e ls e
echo " The f i l e ’ s o m e f i l e ’ does not e x i s t . "
fi
In the above script first we check if the file somefile is readable. If so, we read it
into a variable. If not, we check if it actually exists. If that’s true, we report that it
exists but isn’t readable otherwise it moves to the else condition.
Test Meaning
-s file Non empty file
-f file Is file exist or normal file and not a directory
-d dir Is directory exist and not a file
-w file Is writable file
-r file Is read-only file
-x file Is executable file
4. Logical Operators
You can invert a test by placing the ! operator before the test arguments. For
example, [ ! -f file ] returns true if file is not a regular file. Furthermore, the -a and
-o flags are the logical and and or operators. For example, [ -f file1 -a file2 ].
Operator Meaning
! expression Logical NOT
expression1 -a expression2 Logical AND
expression1 -o expression2 Logical OR
IF ELSE S TAT E M E NT
# ! / b i n / bash
coun t =99
i f [ $count eq 100 ]
then
echo " Count i s 100 "
e ls e
echo " Count i s not 100 "
fi
# ! / b i n / bash
# s c r i p t to see whether argument i s p o s i t i v e or n eg a t i v e
i f [ $ # eq 0 ]
then
echo " $0 : You must supply one i n t e g e r "
exit 1
fi
i f t e s t $1 g t 0
then
echo " $1 i s p o s i t i v e number "
e ls e
echo " $1 i s n e g a t i v e "
fi
IF - E L I F STAT E M ENT
Example:
# ! / b i n / bash
echo " I s i t morning ? P l e a s e answer yes or no "
read tim eo fda y
i f [ $ time ofda y = " y es " ] ; then
echo "Good morning "
e l i f [ $time of d ay = " no " ] ; then
echo " good a f t e r n o o n "
e ls e
echo " Sorry , $ tim e of da y not r e c o g n i ze d . E n t e r yes or no "
exit 1
fi
exit 0
C ASE STAT E M E NT
For each case value, you can match a single string or multiple strings with | (hi|hello
returns true if $1 equals hi or hello in third example), or you can use the * or ? patterns
(what*). To make a default case that catches all possible values other than the case val-
ues specified, use a single * as shown by the final case in the examples. The syntax of
case statement is:
case $ v a r i a b l e name i n
p a t t e r n 1 ) command . . . . . . . command ; ;
p a t t e r n 2 ) command . . . . . . . command ; ;
patternN ) command . . . . . . . command ; ; )
command . . . . . . command ; ;
esac
Examples
# ! / b i n / bash
echo " I s i t morning ? P l e a s e answer yes or no "
read tim eo fda y
# ! / b i n / bash
case $1 i n
bye )
echo Fi n e , bye .
;;
hi|h e l l o )
echo Nice t o se e you .
;;
what )
echo Whatever .
;;
)
echo ’Huh? ’
;;
esac
13 A R IT H M E T I C O P E R ATION S
$((expression))
$(( n1+n2 ))
14 L OOP S
There are two kinds of loops in the shell: for and while loops.
1. For Loop
The basic syntax of for loop is:
f or va ri a bl e_ n a m e i n { l i s t o f v a l u e s }
do
e xe c u t e one f or each i t em i n t h e l i s t u nt i l l i s t i s not f i n i s h e d
r e p e a t a l l s t a t em e n t between do and done
done
Examples:
# ! / b i n / bash
f or i i n 1 2 3 4 5
do
echo " Welcome $ i ti m es "
done
# ! / b i n / bash
i =1
f or day i n Mon Tues Wed Thu F r i
do
echo "Weekday $ ( ( i + + )) : $day "
done
Sample Output:
Weekday 1 : Mon
Weekday 2 : Tue
Weekday 3 : Wed
Weekday 4 : Thu
Weekday 5 : Fri
# ! / b i n / bash
# d e f i n e i n t e r v a l i n f o r l o op
# th e l o op exec ut e from 1 to 5
f or i i n { 1 . . 5 }
do
echo " Welcome $ i ti m es "
done
# ! / b i n / bash
# th e l o op exec ut e from 0 to 10
# w i t h a jump of 2 i n each i n t e r a t i o n
f or i i n { 0 . . 1 0 . . 2 }
do
echo " Welcome $ i ti m es "
done
2. While Loop
The basic syntax of while loop is:
# ! / b i n / bash
while [ c o n d i t i o n ]
do
command_1
command_2
..............
command_N
done
Examples:
# ! / b i n / bash
echo " E n t e r password "
read t r y t h i s
# ! / b i n / bash
# s et n to 1
n=1
# c o n t i nu e u n t i l n equal s 5
while [ $n l e 5 ]
do
echo " Welcome $n t i m e s . "
n=$ ( ( n+1 ) )
done