Previous | Table of Contents | Next |
The order in which commands execute in a shell script is called the flow of the script. In the scripts that you have looked at so far, the flow is always the same because the same set of commands executes every time.
In most scripts, you need to change the commands that execute depending on some condition provided by the user or detected by the script itself. When you change the commands that execute based on a condition, you change the flow of the script. For this reason, the commands discussed in this chapter are called flow control commands. You might also see them referred to as conditional flow control commands because they change the flow of a script based on some condition.
Two powerful flow control mechanics are available in the shell:
The if statement is normally used for the conditional execution of commands, whereas the case statement enables any number of command sequences to be executed depending on which one of several patterns matches a variable first.
In this chapter, I explain how to use flow control in your shell scripts.
The if statement performs actions depending on whether a given condition is true or false. Because the return code of a command indicates true (return code is zero) or false (return code is nonzero), one of the most common uses of the if statement is in error checking. An example of this is covered shortly.
The basic if statement syntax follows:
if list1 then list2 elif list3 then list4 else list5 fi
Both the elif and the else statements are optional. If you have an elif statement, you dont need an else statement and vice versa. An if statement can be written with any number of elif statements.
The flow control for the general if statement follows:
Because the shell considers an if statement to be a list, you can write it all in one line as follows:
if list1 ; then list2 ; elif list3 ; then list4 ; else list5 ; fi ;
Usually this form is used only for short if statements.
A simple use of the if statement is
if uuencode koala.gif koala.gif > koala.uu ; then echo "Encoded koala.gif to koala.uu" else echo "Error encoding koala.gif" fi
Look at the flow of control through this statement:
uuencode koala.gif koala.gif > koala.uu
echo "Encoded koala.gif to koala.uu"
echo "Error encoding koala.gif"
You might have noticed in this example that both the if and then statements appear on the same line. Most shell programmers prefer to write if statements this way in order to make the if statement more concise. The majority of shell programmers claim that this form looks better.
Previous | Table of Contents | Next |