Control Mechanisms of the UNIX Shell - The if control statement
(Page 3 of 4 )
For the decision control we use the “if structure.” This will assure that, depending upon a condition, a command line will or will not be executed. Of course, there will also be an alternative branch containing what should be done if the assumption is false. The syntax for simple decision making is:
if condition_command_line
then
#commands
…
else
#commands
…
fi
We can cascade this one into another with the following syntax:
if condition_command_line
then
#commands
…
elif condition_command_line
#commands
…
else
#commands
…
fi
The conditions of the command line can be many. It can be a text expression with a command like the expr and the test. This we will cover later on. It can be a command line composed of multiple commands with the help of pipes or the upper &&,||. ! structures. If this is the case, after the if, it will test the $? special variable to determine whether or not the command was correctly executed. Before this, it will execute any command standing in the condition_command_line.
This leads to the fact that we can also use it with no conditions, just a command line. In this case it will just test the current value of the $?. What you should also know is that the shell will not allow any empty branch for the “if structure.” If you created a branch, you must do something there. If for some reason you still have nothing to do, call the empty command with the “:” symbol. The example below will show you how to do this:
if cd alfa
then
echo “The directory alfa exits”
else
:
fi
#or
cd alfa
if expr $? = 0
then
echo “The directory alfa exits”
else
:
fi
Most of the time we will use the test command to help us decide a condition. This is a very important command, and very useful; therefore, I have decided to accord to it an entire future article. In it, I will cover in detail how to use it along with the “if structure.”
Next: The expr command >>
More Miscellaneous Articles
More By Gabor Bernat