Here's the syntax of a for loop:
for variable in list
do
command(s)
done
For example:
for file in $*
do
ex - $file < exscript
done
(The command doesn't need to be indented; we indented it for
clarity.)
After we create this shell script, we save it in a file called
correct and make it executable with the chmod
command.
(If you aren't familiar with the chmod command and the
procedures for adding a command to your UNIX search path, see
Learning the UNIX Operating System, published
by O'Reilly & Associates.) Now type:
$ correct sect1 sect2
The for loop in correct will assign each argument
(each file in the list specified by $*, which stands
for all arguments) to the variable file and
execute the ex script on the contents of that variable.
It may be easier to grasp how the for loop works with an
example whose output is more visible.
Let's look at a script to rename files:
for file in $*
do
mv $file $file.x
done
Assuming this script is in an executable file called move,
here's what we can do:
$ ls
ch01 ch02 ch03 move
$ move ch??
$ ls
ch01.x ch02.x ch03.x move
With creativity, you could rewrite the script to rename the
files more specifically:
for nn in $*
do
mv ch$nn sect$nn
done
With the script written this way, you'd specify numbers instead of
filenames on the command line:
$ ls
ch01 ch02 ch03 move
$ move 01 02 03
$ ls
sect01 sect02 sect03 move
The for loop need not take $* (all arguments) as the
list of values to be substituted.
You can specify an explicit list as well. For example:
for variable in a b c d
will assign variable to a, b, c, and
d in turn.
Or you can substitute the output of a command. For example:
for variable in `grep -l "Alcuin" *`
will assign variable in turn to the name of each file in which
grep finds the string Alcuin.
If no list is specified:
for variable
the variable will be assigned to each command-line argument in turn,
much as it was in our initial example.
This is actually not equivalent to:
for variable in $*
but to:
for variable in "$@"
which has a slightly different meaning.
The symbol $* expands to $1, $2, $3,
etc., but the four-character sequence "$@" expands to
"$1", "$2",
"$3", etc.
Quotation marks prevent further interpretation of special characters.
Let's return to our main point and our original script:
for file in $*
do
ex - $file < exscript
done
It may seem a little inelegant to have to use two scripts—the shell
script and the ex script.
And in fact, the shell does provide a way to include an editing script
inside a shell script.