ANDHRA PRADESH
Name : A V N L Sarojini
Designation : Lecturer
Branch : Computer Engineering
Institute : A.A.N.M. & V.V.R.S.R. Poly.,
Gudlavalleru.
Year/Semester : III Semester
Subject : UNIX & C
Subject Code : CM-302
Topic : Shell Programming &
Filtering Techniques
Duration : 50 Min
Sub Topic : Conditional Statements
Teaching Aids : PPTs.
CM304.13 1
Objective
On completion of this period you would be able
to know
Introduction to conditional tests
Using test command
Using test command for numeric test
Using test command for string test
Using test command for file test
if-then-fi conditional statement
if-then-else-fi conditional statement
CM304.13 2
What is Conditional Test?
CM304.13 3
Various conditional statements in shell
CM304.13 4
test command
CM304.13 5
test command Contd..
Example.
$if test ”$answer”=“y”
(or)
$if [“$answer”=“y”]
CM304.13 6
test command Contd..
CM304.13 7
test command
1. Numeric Tests
2. String Tests
3. File Tests
CM304.13 8
test command - Numeric Tests
-eq Equal to
-ne Not Equal to
-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal to
CM304.13 9
test command -Numeric Tests (Example)
$x=5;y=7
$test $x -eq $y
(or)
$x=5;y=7
$[ $x -lt $y ]
CM304.13 10
test command - String Tests
CM304.13 11
test command - String Tests
CM304.13 12
test command -String Tests (Example)
$ans=y
[ “$ans”=“y” ]
[ “$ans”!=“y” ]
[ -n “$ans” ]
[ -z “$ans” ]
CM304.13 13
test command - File tests
CM304.13 14
test command - File tests
CM304.13 15
test command - File tests ( Example)
$[ -f student.lst ]
$[ -x student.lst ]
CM304.13 16
The if-then-fi statement
Syntax:
if test_expression
then
true_block
statement 1
- - -
- - -
statement n
fi
CM304.13 17
The if-then-fi statement
CM304.13 18
Example shell script using if-then-fi
CM304.13 19
Example2
CM304.13 20
The if-then-else-fi statement
Syntax:
if test_expression
then
true_block
else
false_block
fi
CM304.13 21
The if-then-else-fi statement
CM304.13 22
Example shell script using if-then-else-fi
CM304.13 23
Example shell script using if-then-else-fi
sum=`expr $a + $b + $c + $d + $e`
avg=`expr $sum / 5`
if [ $avg -ge 60]
then
echo “Student secured First division”
else
echo “Student secured Second Division”
fi
CM304.13 24
Example2
Write shell script to check whether the number is
even or not.
echo –n “ enter number”
read number
check= `expr $number %2`
if [ $check –eq 0]
then
echo “ the number is even”
else
echo “ the number is odd”
fi
CM304.13 25
Summary
CM304.13 26
Quiz
x=10
if [ $x -ge 2 ]
echo $x
fi
CM304.13 27
Quiz
2.What will be the output of the below program
x=3
y=3.0
if [ $x -eq $y ]
then
echo “ X and Y and equal”
else
echo “X and Y and not equal’
fi
Output
X and Y are equal
CM304.13 28