CHAPTER 12Using Structured Commands
In Chapter 11, “Basic Script Building,” the shell processed each individual command in the order in which it appeared within a shell script. Although this works out fine for sequential operations, many programs require some sort of logic flow control between the commands in the script.
There is a whole command class that allows the shell to skip over script sections based on tested conditions and alter the operation flow. These commands are generally referred to as structured commands.
Quite a few structured commands are available in the Bash shell, so we'll break them up into different chapters. In this chapter, we look at if
-
then
and case
statements.
Working with the if-then Statement
The most basic type of structured command is the if-then
statement. The if-then
statement has the following format:
if command
then
commands
fi
If you're using if-then
statements in other programming languages, this format may be somewhat confusing. In other programming languages, the object after the if
statement is an equation that is evaluated for a TRUE
or FALSE
value. That's not how the Bash shell if
statement works.
The Bash shell if
statement runs the command defined on the if
line. If the exit status of the command (see Chapter 11) is zero (the command completed ...
Get Linux Command Line and Shell Scripting Bible, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.