for arg in
listdo ...handle $arg... done
If you omit the
list, the loop steps through the command-line arguments.
It puts the first command-line argument in arg (or whatever
else you choose to call the
then executes the commands from
Then it puts the next command-line argument in arg, does the loop...
and so on... ending the loop after handling all the arguments.
#!/bin/sh # zpg - UNCOMPRESS FILE(S), DISPLAY WITH pg # Usage: zpg [pg options] file [...files] stat=1 # DEFAULT EXIT STATUS; RESET TO 0 BEFORE NORMAL EXIT temp=/tmp/zpg$$ trap 'rm -f $temp; exit $stat' 0 trap 'echo "`basename $0`: Ouch! Quitting early..." 1>&2' 1 2 15 files= switches= for arg do case "$arg" in -*) switches="$switches $arg" ;; *) files="$files $arg" ;; esac done case "$files" in "") echo "Usage: `basename $0` [pg options] file [files]" 1>&2 ;; *) for file in $files do gzcat "$file" | pg $switches done stat=0 ;; esac
We added a for 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 for loop,
Because the argument starts with a minus sign (
the case treats it as an option.
switches variable is replaced by its previous contents
(an empty string), a space, and
Control goes to the
esac and the loop repeats
with the next argument.
The next argument,
afile, doesn't look like an option.
So now the
files variable will contain a space and
The loop starts over once more, with
Again, this looks like a file, so now
../bfile was the last argument, the loop ends;
has the options and
$files has all the other arguments.
Next, we added another for loop.
This one has the word
in followed by
so the loop steps through the contents of
The loop runs gzcat on each file, piping it to pg with any switches
This way, if
$switches is empty, the shell won't pass an empty
argument to pg.
$switches 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 for loop with any space-separated (actually, -separated) list of words - not just filenames. You don't have to use a shell variable as the list; you can use (backquotes), , or just "hardcode" the list of words:
|44.15 Handling Command-Line Arguments in Shell Scripts||44.17 Handling Arguments with while and shift|