UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 9.11 Repeating a Command with a foreach Loop Chapter 9
Saving Time on the Command Line
Next: 9.13 Multiline Commands, Secondary Prompts
 

9.12 The Bourne Shell for Loop

The Bourne shell for loop is like the C shell foreach loop (9.11): it loops through a list of words, running one or more commands for each word in the list. This saves time when you want to run the same series of commands, separately, on several files.

Let's use the example from the article about foreach:

$ for file in /usr/fran/report /usr/rob/file2 /usr/rob/file3
> do
> cat -t -v $file | pg
> done
   ...Shell runs cat -t -v /usr/fran/report | pg...
   ...Shell runs cat -t -v /usr/rob/file2 | pg...
   ...Shell runs cat -t -v /usr/rob/file3 | pg...
$

The right angle brackets (>) are secondary prompts (9.13); the Bourne shell will keep printing them until you type the command done. Then it runs the loop. You don't have to press RETURN after the do; you can type the first command on the same line after it.

In a shell script, the loop body (the lines between do and done) are usually indented for clarity.

The list after the in doesn't have to be filenames. Among other things, you can use backquotes (9.16) (command substitution), variables (6.8, 6.1), or wildcards (15.1). For example, you could have typed the above loop this way:

$ for file in /usr/fran/report /usr/rob/file[23]
> do cat -t -v $file | pg
> done

If you want the loop to stop before or after running each command, add the Bourne shell read command (44.13). It reads keyboard input and waits for a RETURN. In this case, you can probably ignore the input; you'll use read to make the loop wait. For example, to make the above loop prompt before each command line:

$ for file in /usr/fran/report /usr/rob/file[23]
> do
> echo -n "Press RETURN to see $file-"
> read x
> cat -t -v $file | pg
> done
Press RETURN to see /usr/fran/report-
[RETURN]
   Shell runs cat -t -v /usr/fran/report | pg...
Press RETURN to see /usr/rob/file2-
[RETURN]
   Shell runs cat -t -v /usr/rob/file2 | pg...
Press RETURN to see /usr/rob/file3-
[RETURN]
   Shell runs cat -t -v /usr/rob/file3 | pg...

Article 44.16 has more information about the for loop. Article 45.16 shows how to make a for loop read the standard input instead of a list of arguments.

- JP


Previous: 9.11 Repeating a Command with a foreach Loop UNIX Power ToolsNext: 9.13 Multiline Commands, Secondary Prompts
9.11 Repeating a Command with a foreach Loop Book Index9.13 Multiline Commands, Secondary Prompts

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System