image

Using Structured Commands

IN THIS CHAPTER

Working with the if-then statement

Nesting ifs

Understanding the test command

Testing compound conditions

Using double brackets and parentheses

Looking at case

In the shell scripts presented in Chapter 11, the shell processed each individual command in the shell script in the order it appeared. This works out fine for sequential operations, where you want all the commands to process in the proper order. However, this isn't how all programs operate.

Many programs require some sort of logic flow control between the commands in the script. There is a whole command class that allows the script to skip over executed commands based on tested conditions. These commands are generally referred to as structured commands.

The structured commands allow you to alter the operation flow of a program. Quite a few structured commands are available in the bash shell, so we'll look at them individually. 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 ...

Get Linux Command Line and Shell Scripting Bible, 3rd 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.