Previous Section  < Day Day Up >  Next Section

Chapter 5. Flow Control

If you are a programmer, you may have read the last chapter—with its claim at the outset that bash has an advanced set of programming capabilities—and wondered where many of the features from conventional languages were. Perhaps the most glaringly obvious "hole" in our coverage thus far concerns flow control constructs like if, for, while, and so on.

Flow control gives a programmer the power to specify that only certain portions of a program run, or that certain portions run repeatedly, according to conditions such as the values of variables, whether or not commands execute properly, and others. We call this the ability to control the flow of a program's execution.

Almost every shell script or function that's been shown thus far has had no flow control—they have just been lists of commands to be run! Yet bash, like the C and Bourne shells, has all of the flow control abilities you would expect and more; we will examine them in this chapter. We'll use them to enhance the solutions to some of the programming tasks we saw in the last chapter and to solve tasks that we will introduce here.

Although we have attempted to explain flow control so that nonprogrammers can understand it, we also sympathize with programmers who dread having to slog through yet another tabula rasa explanation. For this reason, some of our discussions relate bash's flow-control mechanisms to those that programmers should know already. Therefore you will be in a better position to understand this chapter if you already have a basic knowledge of flow control concepts.

bash supports the following flow control constructs:


if/else

Execute a list of statements if a certain condition is/is not true


for

Execute a list of statements a fixed number of times


while

Execute a list of statements repeatedly while a certain condition holds true


until

Execute a list of statements repeatedly until a certain condition holds true


case

Execute one of several lists of statements depending on the value of a variable

In addition, bash provides a new type of flow-control construct:


select

Allow the user to select one of a list of possibilities from a menu

We will now cover each of these in detail.

    Previous Section  < Day Day Up >  Next Section