44.17 Handling Arguments with while and shift
A
for
loop (44.16
)
is great if you want to handle all of the command-line arguments to a
script, one by one. But, as is often the case, some arguments are
options that have their own arguments. For example, in the command
while [ $# -gt 0 ] do case "$1" in -a) options="$options $1";; ... -f) options="$options $1" argfile="$2" shift ;; *) files="$files $1";; esac shift done
The trick is this: shift
removes an argument from the script's
argument list, shifting all the others over by one (
Meanwhile, all the case
has to do is to test We assume that anything without a minus sign is a file. This last case could be written more robustly with a test to be sure the argument is a file. Here's an example of a simple script that uses this construct to pass an option and some files to pr and from there to a program that converts text to PostScript and on to the print spooler: while [ $# -ne 0 ] do case $1 in +*) pages="$1" ;; *) if [ -f "$1" ]; then files="$files $1" else echo "$0: file $1 not found" 1>&2 fi;; esac shift done pr $pages $files | psprint | lpr
This approach is perhaps obsolete if you have
getopts
(44.18
)
,
since getopts
lets you recognize option strings like
- |
|