0% found this document useful (0 votes)
84 views

Lab 05 and 06 Shell Scripting

loops and conditional structure in operating system in detail

Uploaded by

Shahid Zikria
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

Lab 05 and 06 Shell Scripting

loops and conditional structure in operating system in detail

Uploaded by

Shahid Zikria
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Lab Manual 05 and 06

Shell scripting

Operating systems Lab


COSC-2206

Copyright © 2019 Rida Fatima

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).

F IL E M ODES AND PE RMIS SION S

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.

File Mode Explanation

r Means that the file is readable.


w Means that the file is writable.
x Means that the file is executable (you can run it
as a program).
- Means nothing

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:

$ chmod g+r file


$ chmod o+r file

Or you could do it all in one shot:

$ chmod go+r file

To remove these permissions, use go-r instead of go+r.

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

$ chmod 700 file

User Group Other 3 Digit No. Description


r w x r w x r w x
1 0 0 0 0 0 0 0 0 400 user: read
0 0 0 1 0 0 0 0 0 040 group: read
1 1 1 0 0 1 0 0 1 711 user: read/write/execute; group, other: execute
1 1 0 1 0 0 1 0 0 644 user: read/write; group, other: read
1 1 0 0 0 0 0 0 0 600 user: read/write; group, other: none

Table 1: Examples of chmod with 3 Digit numbers

R UNN IN G S HELL S C R IP TS

Execute your script as

./script-name

9 I M P O RTAN T P O INT S

Following are some important points while writing a script:

1. # is used to write comments in your script

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

In Linux shell there are three types of variables:

1. User defined or shell variables

2. System or Environment variables

3. Parametric variables

U SER D E FINED OR S HELL VA RIA BL E S

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

$STUFF (for example, try running echo $STUFF).

Rules for defining variables:

1. Variable name must begin with Alphanumeric character or underscore character,


followed by one or more Alphanumeric character.

2. Don’t put spaces on either side of the equal sign when assigning value to variable.

3. Variables are case-sensitive, just like filename in Linux.

4. You can define NULL variable as

var=

var=""

5. Do not use ?,* etc, to name your variable names.

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

will output /usr/local/bin:/usr/bin:/bin


To tell the shell to look in more places for programs, change the PATH environ-
ment variable. For example, by using this command, you can add a directory dir
to the beginning of the path so that the shell looks in dir before looking in any of
the other PATH directories.
$ PATH=dir:$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.

1. Individual Arguments: $1, $2, ...


$1, $2, and all variables named as positive nonzero integers contain the values of
the script parameters, or arguments. For example, say the name of the following
script is pshow:
# ! / b i n / bash
echo F i r s t argument : $1
echo Th ir d argument : $3

Try running the script as follows to see how it prints the arguments:

$ ./pshow one two three

Output looks like:


First argument: one
Third argument: three

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:

echo $0: $errormsg

4. Process ID: $$
The $$ variable holds the process ID of the shell.

11 I N P U T VALU ES

The read command is used to get a line of input into a variable.

# ! / 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 ! "

Rules to input variables:


1. Each argument must be a variable name without the leading "$".
2. The built in command reads a line of input and separates the line into individual
words using the "IFS" inter field separator.
3. Each word in the line is stored in a variable from left to right.
4. The first word is stored in the first variable, the second word to the second vari-
able and so on.
5. If there are fewer variables than words, then all remaining words are then as-
signed to the last variable.
6. If you have more variables than words defined, then any excess variables are set
to null.

# ! / 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 "

12 C ON D IT ION A L S TAT EM E NTS

The Bourne shell has special constructs for conditionals, such as


1. If statement
2. If-else statement
3. If-elif statement
4. Case Statement
I F S TAT E M ENT

The basic syntax of if statements is:


# ! / b i n / bash
i f [ c o n d i t i o n a l e x p r e ss i o n ]
then
statement1
statement2
fi

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.

Figure 2: Conditions for test and expressions

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

Table 2: String Comparisons

-z and -n work with the string enclosed within double quotes.


# ! / b i n / bash
# S t r i n g Comparisons

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

3. Test for file and directory


Most file tests that are commonly used are unary operations because they require
only one argument: the file to test.
# ! / b i n / bash
s o m e f i l e =a . t x t
i f [ r $ s o m e f i l e ] ; then
c o n t e n t =$ ( cat $ s o m e f i l e )
echo $ c o n t e n t
e l i f [ f $ s o m e f i l e ] ; then
echo " The f i l e ’ s o m e f i l e ’ e x i s t s but i s not r e a d a b l e t o t h e s c r i p t . "

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

Table 3: Test for File and Directory

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

Table 4: Logical Operators

IF ELSE S TAT E M E NT

The basic syntax of if-else statements is:


if c ondition
then
e xe c u t e a l l commands upto e ls e
e ls e
e xe c u t e a l l commands upto f i
fi

Examples using if-else


# ! / 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 ls e
echo " good a f t e r n o o n "
fi

# ! / 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

The basic syntax of if-elif statements is:


if c ondition
then
.............
e l i f condition
then
.............
e ls e
.............
fi

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

case " $t ime ofda y " i n


yes ) echo "Good Morning " ; ;
no ) echo "Good Afternoon " ; ;
y ) echo "Good Morning " ; ;
n ) echo "Good Afternoo n " ; ;
) echo " Sorry , answer n ot r e c o g n i ze d " ; ;
esac

# ! / 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

Arithmetic expansion and evaluation is done by placing an integer expression using


the following format:

$((expression))

$(( n1+n2 ))

The shell script below includes some arithmetic operations.


# ! / b i n / bash
clear
echo " h e l l o world "
var1 = 1 0 ;
var2 = 2 0 ;
var3=$ ( ( $var 1 + $var2 ));
var4=$ ( ( $var 1 $var2 ));
var5=$ ( ( $var 1 $var2 ));
var6=$ ( ( $var 1 / $var2 ));
echo $va r3 ;
echo $va r4 ;
echo $va r5 ;
echo $va r6 ;
exit

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

while [ " $ t r y t h i s " ! = " s e c r e t " ] ; do


echo " Sorry , t r y a g a i n "
read t r y t h i s
done

# ! / 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

You might also like