O'Reilly logo

Learning the Korn Shell, 2nd Edition by Bill Rosenblatt, Arnold Robbins

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 only take 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 the Korn shell — 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, with the normal for loop, 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 arithmetic for loop, which we’ll see in Chapter 6, to do that.)

However, the for loop is ideal for working with arguments on the command line and with sets of files (e.g., all files in a given directory). We’ll look ...

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