Unix Shell Script Conditional Statements
April 15, 2007 by Mark Marucot
Conditional statements are use to perform specific action/s based on a given conditions
if Statement
The if statement performs specific statement/s if the condition is met otherwise the set of statements is skipped.
-
if [ condition ]
-
then
-
# if-code
-
fi
Wrong
-
if [$foo = "bar" ]
Correct
-
if [ "$foo" = "bar" ]
Note: Bracket ([) is actually a program which means it is required to place spaces in between the condition because it reads the next group of words or letters as arguments or program parameters. Syntax should be if [ space <var1> space <operator> space <var2> space ]
if .. else Statement
The if .. else statement performs specific statement/s if the condition is met otherwise the another statement/s is performed.
-
if [ condition ]
-
then
-
# if-code
-
else
-
# else-code
-
fi
if .. else if .. else Statement
The if .. else if .. else statement performs specific statement/s if there are three or more conditions.
-
if [ condition1 ]; then
-
# if-code
-
elif [ condition2 ]; then
-
# if-code
-
else
-
# else-code
-
fi




Comments
Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!