If Statements
If statements test conditions and execute commands when the condition is true. The if statement has the following general format: if [ condition ]
then
commands
elif [ condition ]
then
commands
else
commands
fi
The if statements begins with if and ends with fi (if spelled backward). All three parts are not required. Only the if section is required. The elif (elseif) and the else sections are optional. Also, notice that the if section and the elif section start with then, but the else section does not. You can use more than one elif section, but only one if and else section is allowed. An if statement can be as simple as: if [ $x -eq 1 ]
then
echo Hello
fi
A more complex statement is: if [ $day = "Saturday" -o $day = "Sunday" ]
then
echo Sleep in
elif [ $day = "Monday" ]
then
echo Call in sick
else
echo Go to work
fi
You can nest if statements inside of if statements, as follows: if [ $city = "Miami" ]
then
if [ $name = "John" ]
then
echo Hello John in Miami
else
echo Hello friend in Miami
fi
fi
|