Control Flow
Control flow is the primary feature of a shell script, and familiar constructs are at the programmer’s disposal. Shell scripts are structured using a combination of reserved words and control operators to form compound commands and function definitions. The general term command encompasses simple commands, discussed in the previous module, compound commands, and function definitions.
Background
Before discussing the control flow, we must understand the basics of reserved words and control operators, and how the concept of exit status is used and propagated when commands are composed. Additionally, we need to formalize the shell grammar to understand the relationships between some of the structures we have already covered, such as pipelines, and those we are about to cover: compound commands and shell functions.
Compound Commands
Compound commands are commands which are constructed of one or more compound-lists, and an assortment of operators and reserved words. Since compound lists can contain compound commands, compound commands can nest arbitrarily, as shown in the example below with several different compound command constructs,
{
...
{
...
if
...
then
...
else
while
...
do
...
done
fi
...
}
...
}
There are three main categories of compound commands. The shell offers two grouping constructs, subshells and brace groups, which can be used to group blocks of commands together. The shell also includes three types of loops, the while, until, and for loops. Finally, the shell has two conditional constructs: if and case.
Shell Functions
A shell function is a user-defined name that is called as a simple command to execute a pre-defined compound command (the function body) with new positional parameters. Functions must be defined before they can be used, which is done with a function definition command.