Unix
In this tutorial we will learn about If Else conditional statement in Shell Programming.
We use the If statement to make decisions whether to execute a block of code or not based on some condition.
Following is the syntax of the if statement.
if [ condition ]
then
# if block code
fi
Where, condition
is some condition which if evaluates to true then the if block code is executed otherwise, it is ignored.
The fi
(reverse of if
) marks the end of the if statement.
In the following example we will use the ==
is equal operator to check if the two numbers are equal.
#!/bin/sh
# take two numbers from the user
echo "Enter two numbers: "
read a b
# check
if [ $a == $b ]
then
echo "Numbers are equal."
fi
echo "End of script."
Output:
$ sh if.sh
Enter two numbers:
10 20
End of script.
$ sh if.sh
Enter two numbers:
10 10
Numbers are equal.
End of script.
In the first run the if block is not executed as 10 is not equal to 20. In the second run the if block is executed as 10 is equal to 10.
Following is the syntax of the if else statement.
if [ condition ]
then
# if block code
else
# else block code
fi
Where, condition
is some condition which if evaluates to true then the if block code is executed otherwise, else block code is executed.
In the following example we will print "Numbers are equal" if they are equal otherwise, "Numbers are not equal".
#!/bin/sh
# take two numbers from the user
echo "Enter two numbers: "
read a b
# check
if [ $a == $b ]
then
echo "Numbers are equal."
else
echo "Numbers are not equal."
fi
echo "End of script."
Output:
$ sh if-else.sh
Enter two numbers:
10 20
Numbers are not equal.
End of script.
Following is the syntax of the if elif else statement.
if [ condition ]
then
# if block code
elif [ condition2 ]
then
# elif block code
else
# else block code
fi
Where, condition
is some condition which if evaluates to true then the if block code is executed. If it is false then, we check the elif condition. If that too is false then we execute the else block if it is present.
We will use the modulus operator %
to check if the number is odd or even.
If a number is divisible by 2 and gives no remainder then it is an even number.
#!/bin/sh
# take a numbers from the user
echo "Enter a number: "
read a
# check
if [ $a == 0 ]
then
echo "It's zero."
elif [ `expr $a % 2` == 0 ]
then
echo "It's even."
else
echo "It's odd."
fi
echo "End of script."
Output:
$ sh if-elif-else.sh
Enter a number:
0
It's zero.
End of script.
$ sh if-elif-else.sh
Enter a number:
10
It's even.
End of script.
$ sh if-elif-else.sh
Enter a number:
11
It's odd.
End of script.
ADVERTISEMENT