O'Reilly logo

Learning the bash Shell, Second Edition by Bill Rosenblatt, Cameron Newham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

for

The most obvious enhancement we could make to the previous script is the ability to report on multiple files instead of just one. Tests like -e and -d take only single arguments, so we need a way of calling the code once for each file given on the command line.

The way to do this—indeed, the way to do many things with bash—is with a looping construct. The simplest and most widely applicable of the shell’s looping constructs is the for loop. We’ll use for to enhance fileinfo soon.

The for loop allows you to repeat a section of code a fixed number of times. During each time through the code (known as an iteration), a special variable called a loop variable is set to a different value; this way each iteration can do something slightly different.

The for loop is somewhat, but not entirely, similar to its counterparts in conventional languages like C and Pascal. The chief difference is that the shell’s for loop doesn’t let you specify a number of times to iterate or a range of values over which to iterate; instead, it only lets you give a fixed list of values. In other words, you can’t do anything like this Pascal-type code, which executes statements 10 times:

for x := 1 to 10 do
begin
    statements...
            end

(You need the while construct, which we’ll see soon, to construct this type of loop. You also need the ability to do integer arithmetic, which we will see in Chapter 6.)

However, the for loop is ideal for working with arguments on the command line and with sets of files (e.g., all ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required