Department of Computer Science
Subject Name : Linux & Shell Programming
Subject Code : 43A
Class : II B.Sc. CS
Semester : IV
Prepared by : Dr.R.Aswanandini
Assistant Professor
Department of Computer Science
KG College of Arts and Science
Unit - V
CONDITIONAL EXECUTION IN
SHELL SCRIPTS
UNIT V
• Using Conditional Execution in Shell Scripts: Conditional Execution –
The case...esac Construct. Managing repetitive tasks using Shell
Scripts: Using Iteration in Shell Scripts –The while construct –until
construct –for construct –break and continue commands –Simple
Programs using Shell Scripts.
CONDITIONAL EXECUTION IN SHELL
SCRIPTS
• Linux Shell supports conditional statements which are used to perform
different actions based on different conditions. We will now understand
two decision-making statements here −
• The if...else statement
• The case...esac statement
The if...else statements
• If else statements are useful decision-making statements which can be
used to select an option from a given set of options.
• Linux Shell supports following forms of if…else statement:
• if...fi statement
• if...else...fi statement
• if...elif...else...fi statement
• if...fi statement:The if...fi statement is the fundamental control
statement that allows Shell to make decisions and execute statements
conditionally.
• if [ expression ]
• then
• Statement(s) to be executed if expression is true
• fi
• #!/bin/sh
• a=10
• b=20
• if [ $a == $b ]
• then
• echo "a is equal to b“
• fi
• if [ $a != $b ]
• then
• echo "a is not equal to b“
• fi
if...else...fi :
• The if...else...fi statement is the next form of control statement that
allows Shell to execute statements in a controlled way and make the
right choice.
• if [ expression ]
• then
• Statement(s) to be executed if expression is true
• else
• Statement(s) to be executed if expression is not true
• fi
• #!/bin/sh
• a=10
• b=20
• if [ $a == $b ]
• then
• echo "a is equal to b“
• else
• echo "a is not equal to b“
• fi
if...elif...else...fi statement :
• The if...elif...fi statement is the one level advance form of control
statement that allows Shell to make correct decision out of several
conditions.
• if [ expression 1 ]
• then
• Statement(s) to be executed if expression 1 is true
• elif [ expression 2 ]
• then
• Statement(s) to be executed if expression 2 is
• true
• elif [ expression 3 ]
• then
• Statement(s) to be executed if expression 3 is true
• else
• Statement(s) to be executed if no expression is true
• fi
• #!/bin/sh
• a=10
• b=20
• if [ $a == $b ]
• then
• echo "a is equal to b“
• elif [ $a -gt $b ]
• then
• echo "a is greater than b“
• elif [ $a -lt $b ]
• then
• echo "a is less than b“
• else
• echo "None of the condition met“
• fi
Unit - V
CONDITIONAL EXECUTION IN
SHELL SCRIPTS
Control Statements
• Without control statements, execution within a shell
scripts flows from one statement to the next in
succession.
• Control statements control the flow of execution in a
programming language
• The three most common types of control statements:
• conditionals: if/then/else, case, ...
• loop statements: while, for, until, do, ...
• branch statements: subroutine calls (good), goto (bad)
for Loops
• for loops allow the repetition of a command for a specific set of
values
• Syntax:
for var in value1 value2 ...
do
command_set
done
• command_set is executed with each value of var (value1, value2, ...) in
sequence
for Loop Example (1)
#!/bin/sh
# timestable – print out a multiplication table
for i in 1 2 3
do
for j in 1 2 3
do
value=`expr $i \* $j`
echo -n "$value "
done
echo
done
for Loop
#!/bin/sh Example (2)
# file-poke – tell us stuff about files
files=`ls`
for i in $files
do
echo -n "$i "
grep $i $i
done
• Find filenames in files in current directory
for Loop
#!/bin/sh Example (3)
# file-poke – tell us stuff about files
for i in *; do
echo -n "$i "
grep $i $i
done
• Same as previous slide, only a little more
condensed.
The test Command – Integer Tests
• Integers can also be compared:
• Use -eq, -ne, -lt, -le, -gt, -ge
• For example:
#!/bin/sh
smallest=10000
for i in 5 8 19 8 7 3; do
if test $i -lt $smallest; then
smallest=$i
fi
done
echo $smallest
Use of [ ]
• The test program has an alias as [ ]
• Each bracket must be surrounded by spaces!
• This is supposed to be a bit easier to read.
• For example:
#!/bin/sh
smallest=10000
for i in 5 8 19 8 7 3; do
if [ $i -lt $smallest ] ; then
smallest=$i
fi
done
echo $smallest
Reading Variables from Standard Input (2)
• Example:
% read X Y Z
Here are some words as input
% echo $X
Here
% echo $Y
are
% echo $Z
some words as input
The case Statement
• The case statement supports multiway branching based on the value of a single string.
• General form:
case string in
pattern1)
command_set_11
;;
pattern2)
command_set_2
;;
…
esac
case Example
#!/bin/sh
echo -n 'Choose command [1-4] > '
read reply
Use the pipe symbol “|” as a logical
echo
or between several choices.
case $reply in
"1")
date
;;
"2"|"3")
pwd
;;
"4")
ls
;;
Provide a default case when no
*)
other cases are matched.
echo Illegal choice!
;;
esac
Unit - V
CONDITIONAL EXECUTION IN
SHELL SCRIPTS
Control Statements
• Without control statements, execution within a shell
scripts flows from one statement to the next in
succession.
• Control statements control the flow of execution in a
programming language
• The three most common types of control statements:
• conditionals: if/then/else, case, ...
• loop statements: while, for, until, do, ...
• branch statements: subroutine calls (good), goto (bad)
for Loops
• for loops allow the repetition of a command for a specific set of
values
• Syntax:
for var in value1 value2 ...
do
command_set
done
• command_set is executed with each value of var (value1, value2, ...) in
sequence
for Loop Example (1)
#!/bin/sh
# timestable – print out a multiplication table
for i in 1 2 3
do
for j in 1 2 3
do
value=`expr $i \* $j`
echo -n "$value "
done
echo
done
for Loop
#!/bin/sh Example (2)
# file-poke – tell us stuff about files
files=`ls`
for i in $files
do
echo -n "$i "
grep $i $i
done
• Find filenames in files in current directory
for Loop
#!/bin/sh Example (3)
# file-poke – tell us stuff about files
for i in *; do
echo -n "$i "
grep $i $i
done
• Same as previous slide, only a little more
condensed.
The test Command – Integer Tests
• Integers can also be compared:
• Use -eq, -ne, -lt, -le, -gt, -ge
• For example:
#!/bin/sh
smallest=10000
for i in 5 8 19 8 7 3; do
if test $i -lt $smallest; then
smallest=$i
fi
done
echo $smallest
Use of [ ]
• The test program has an alias as [ ]
• Each bracket must be surrounded by spaces!
• This is supposed to be a bit easier to read.
• For example:
#!/bin/sh
smallest=10000
for i in 5 8 19 8 7 3; do
if [ $i -lt $smallest ] ; then
smallest=$i
fi
done
echo $smallest
Reading Variables from Standard Input (2)
• Example:
% read X Y Z
Here are some words as input
% echo $X
Here
% echo $Y
are
% echo $Z
some words as input
The case Statement
• The case statement supports multiway branching based on the value of a single string.
• General form:
case string in
pattern1)
command_set_11
;;
pattern2)
command_set_2
;;
…
esac
case Example
#!/bin/sh
echo -n 'Choose command [1-4] > '
read reply
Use the pipe symbol “|” as a logical
echo
or between several choices.
case $reply in
"1")
date
;;
"2"|"3")
pwd
;;
"4")
ls
;;
Provide a default case when no
*)
other cases are matched.
echo Illegal choice!
;;
esac
Unit - V
The while Loop
&The until Loop
The while Loop
• While loops repeat statements as long as the next Unix
command is successful.
• For example:
#!/bin/sh
i=1
sum=0
while [ $i -le 100 ]; do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo The sum is $sum.
The until Loop
• Until loops repeat statements until the next Unix command
is successful.
• For example:
#!/bin/sh
x=1
until [ $x -gt 3 ]; do
echo x = $x
x=`expr $x + 1`
done
Command Line Arguments (1)
• Shell scripts would not be very useful if we could not pass
arguments to them on the command line
• Shell script arguments are “numbered” from left to right
• $1 - first argument after command
• $2 - second argument after command
• ... up to $9
• They are called “positional parameters”.
Command Line Arguments (2)
• Example: get a particular line of a file
• Write a command with the format:
getlineno linenumber filename
#!/bin/sh
head -$1 $2 | tail -1
• Other variables related to arguments:
• $0 name of the command running
• $* All the arguments (even if there are more than 9)
• $# the number of arguments
Command Line Arguments (3)
• Example: print the oldest files in a directory
#! /bin/sh
# oldest -- examine the oldest parts of a directory
HOWMANY=$1
shift
ls -lt $* | tail +2 | tail $HOWMANY
• The shift command shifts all the arguments to the left
• $1 = $2, $2 =$3, $3 = $4, ...
• $1 is lost (but we have saved it in $HOWMANY)
• The value of $# is changed ($# - 1)
• useful when there are more than 9 arguments
• The “tail +2” command removes the first line.
More on Bourne Shell Variables (1)
• There are three basic types of variables in
a shell script:
• Positional variables ...
• $1, $2, $3, ..., $9
• Keyword variables ...
• Like $PATH, $HOWMANY, and anything
else we may define.
• Special variables ...
More on Bourne Shell Variables (2)
• Special variables:
• $*, $# -- all the arguments, the number of
the arguments
• $$ -- the process id of the current shell
• $? -- return value of last foreground
process to finish
-- more on this one later
• There are others you can find out about with man sh
Unit - V
The break and continue
Statements
The break and continue Statements
• break
– Causes immediate exit from a while, for, do/while or
–switch
Programstructure
execution continues with the first statement after the structure
– Common uses of the break statement
• Escape early from a loop
• Skip the remainder of a switch structure
The break and continue Statements (II)
• continue
– Skips the remaining statements in the body of a while, for or
do/while structure
• Proceeds with the next iteration of the loop
– while and do/while
• Loop-continuation test is evaluated immediately after the
continue statement is executed
– for structure
• Increment expression is executed, then the loop-continuation test is evaluated
1 /* Fig. 4.12: fig04_12.c
2 Using the continue statement in a for Outline
3 #include*/<stdio.h>
structure
4
5 int main() 6 { 1. Initialize variable
7 int x; 8
9
2. Loop
10
11 for ( x = 1; x <= 10; x++ ) {
12 3. Print
13 if ( x == 5 )
14 continue; /* skip remaining code in if x
15
loop only == 5 */
16 }
17 printf( "%d ", x );
18 printf( "\nUsed continue to skip printing
19 return 0;
the value 5\n" );
20}
1 2 3 4 6 7 8 9 10 Program Output
Used continue to skip printing the value 5
2000 Prentice Hall, Inc. All rights
The break Keyword
false
Continuation
condition?
true
Statement(s)
break
Statement(s)
Next
Statement
break
// Using break to exit a loop (break.c). #include
<stdio.h>
main() {
int i;
for(i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10 printf("i: %d
\n", i);
}
printf("Loop complete.");
}
The continue Keyword false
Continue
condition?
true
Statement(s)
continue
Statement(s)
Next
Statement