Sometimes you want a script that will step through the command-line arguments
one by one.
gives you all of them at once.)
The Bourne shell
loop can do this.
loop looks like this:
for arg in
If you omit the
, the loop steps through the command-line arguments.
It puts the first command-line argument in
else you choose to call the
shell variable (
then executes the commands from
Then it puts the next command-line argument in
, does the loop...
and so on... ending the loop after handling all the arguments.
For an example of a
loop, let's hack on the
# zpg - UNCOMPRESS FILE(S), DISPLAY WITH pg
# Usage: zpg [pg options] file [...files]
stat=1 # DEFAULT EXIT STATUS; RESET TO 0 BEFORE NORMAL EXIT
trap 'rm -f $temp; exit $stat' 0
trap 'echo "`basename $0`: Ouch! Quitting early..." 1>&2' 1 2 15
case "$arg" in
-*) switches="$switches $arg" ;;
*) files="$files $arg" ;;
case "$files" in
"") echo "Usage: `basename $0` [pg options] file [files]" 1>&2 ;;
*) for file in $files
do gzcat "$file" | pg $switches
We added a
loop to get and check each command-line argument.
For example, let's say that a user typed:
zpg -n afile ../bfile
The first pass through the
Because the argument starts with a minus sign (
treats it as an option.
variable is replaced by its previous contents
(an empty string), a space, and
Control goes to the
and the loop repeats
with the next argument.
The next argument,
, doesn't look like an option.
So now the
variable will contain a space and
The loop starts over once more, with
Again, this looks like a file, so now
was the last argument, the loop ends;
has the options and
has all the other arguments.
Next, we added another
This one has the word
so the loop steps through the contents of
The loop runs
on each file, piping it to
with any switches
This way, if
is empty, the shell won't pass an empty
has more than one switch, the shell will break the
switches into separate arguments at the spaces and pass them individually to
You can use a
loop with any space-separated (actually,
list of words - not just filenames.
You don't have to use a shell variable as the list;
you can use
command substitution (
shell wildcards (
or just "hardcode" the list of words:
for person in Joe Leslie Edie Allan
echo "Dear $person," | cat - form_letter | lpr
commands handle command-line arguments in a more standard way than