Control Structure in Shell Script
Control Structure in Shell Script
if (($a == $b ))
then
#If they are equal then print this
echo "a is equal to b"
else
#else print this
echo "a is not equal to b"
fi
if..elif..else..fi statement (Else If ladder)
• To use multiple conditions in one if-else block,
then the elif keyword is used in shell. If
expression1 is true then it executes statement
1 and 2, and this process continues. If none of
the conditions is true then it processes else
part.
Syntax:
if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi
• # if condition is true
• if [ "myfile" == "myfile" ];
• then
• echo "true condition"
• fi
•
• # if condition is false
• if [ "myfile" == "yourfile" ];
• then
• echo "false condition"
• fi
In this example, we demonstrate the usage of if
statement with a simple scenario of comparing two
strings:
Nested If Else
• Just like nested if statement, the if-else
statement can also be used inside another if-
else statement. It is called nested if-else in
Bash scripting.
• Following is an example explaining how to
make use of the nested if-else statement in
Bash:
• read -p "Enter a value:" value
• if [ $value -gt 9 ];
• then
• if [ $value -lt 11 ];
• then
• echo "$value>9, $value<11"
• else
• echo "The value you typed is greater than 9."
• fi
• else echo "The value you typed is not greater than 9."
• fi
• #!/bin/bash
• read -p "Enter a number of quantity:" num
• if [ $num -gt 100 ];
• then
• echo "Eligible for 10% discount"
• elif [ $num -lt 100 ];
• then
• echo "Eligible for 5% discount"
• else
• echo "Lucky Draw Winner"
• echo "Eligible to get the item for free"
• fi
• #!/bin/bash
• read -p "Enter a number of quantity:" num
• if [ $num -gt 200 ];
• then
• echo "Eligible for 20% discount"
•
• elif [[ $num == 200 || $num == 100 ]];
• then
• echo "Lucky Draw Winner"
• echo "Eligible to get the item for free"