9.11 Repeating a Command with a foreach LoopWhen some people need to repeat a command on several files, the first thing they think of is C shell history ( 11.5 ) :
That kind of thing can be easier with the C shell's foreach loop. (In the Bourne and Korn shells, use a for ( 9.12 ) loop.) You give the loop a list of the words that will change each time the command line is run. In this example, it's a list of filenames. The loop will step through the words, one by one, storing a word into a shell variable ( 6.8 ) , then running the command(s). The loop goes on until it has read all the words. For example:
%
The question marks (
The list between the parentheses doesn't have to be filenames.
Among other things, you can use
wildcards (
1.16
)
,
backquotes (
9.16
)
(command substitution),
variables (
6.8
,
6.1
)
,
and the C shell's handy
curly brace (
%
If you want the loop to stop before or after running each command, add the C
shell operator
The loop parameters don't need to be filenames. For instance, you could send a personalized mail ( 1.33 ) message to five people this way: [1]
The first line of the first letter will be "Dear John,"; the second letter "Dear Cathy,"; and so on. Want to take this idea further? It's a part of shell programming ( 44.1 ) . I usually don't recommend ( 47.2 ) shell programming with the C shell, but this is a handy technique to use interactively. - |
|