|
|
Nested if..else
Nested if else statements can be useful to check multiple conditions. For example, given a number first check whether it is positive or negative then test the range in the respective domains.
Syntax:
if condition
then
if condition
then
statement1
else
statement2
fi
else
statement3
fi
Example :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
read x | |
if [ $x -ge 0 ] | |
then | |
if [ $x -ge 10 -a $x -le 100 ] | |
then | |
echo "$x is between 10 and 100" | |
else | |
echo "$x is between 0 and 9" | |
fi | |
else | |
if [ $x -le -10 -a $x -ge -100 ] | |
then | |
echo "$x is between -10 and -100" | |
else | |
echo "$x is between -1 and -9" | |
fi | |
fi |
if..elif statements
Syntax
if condition1
then
statement1
elif condition2
then
statement2
elfi condition3
then
statement3
else
#if none of the conditions are satisfied
statement4
fi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo "Enter your favourite tech company" | |
read x | |
if [ -z $x ] | |
then | |
echo "You have entered a NULL string." | |
elif [ $x = "Apple" ] | |
then | |
echo "I guess you might be liking iphone and ipad " | |
elif [ $x = "Google" ] | |
then | |
echo "I guess you might be liking Android and Chrome" | |
elif [ $x = "Microsoft" ] | |
then | |
echo "I guess you might be liking Windows and Office" | |
elif [ $x = "Nokia" ] | |
then | |
echo "Sorry who Nokia?" | |
else | |
echo "Sorry search failed :( " | |
fi |
No comments:
Post a Comment