Processing Command-Line Options in the Shell
Ed Schaefer
If your shell scripts are to move beyond the ad hoc, you will need to process
command-line options beyond the simple:
unixscript $1 $2 $3
And, if other users and software developers are going to use your scripts, a concise
approach to processing command-line options will simplify using these options
and trapping errors.
This article presents three advanced methods of processing command-line options.
The first method is using the UNIX built-in command, getopts, to do the
parsing. The other two methods, coding parameters and keyword=value,
require writing code to process the command-line options using a while
loop and the shift command.
Using getopts
System V supports a built-in command-line parser command, getopts,
for both the Bourne and Korn shells. The getopts command placed in a
loop will parse single character flags, provided that the flag exists in the
argument string succeeding the getopts command and the flag is preceded
by a dash.
the general form of getopts is:
getopts optionstring name
where optionstring is one or more valid option letters that getopts
recognizes and name is a variable that getopts shifts into
with each execution. If an option requires an argument, such as -z argument
a colon follows the option letter.
With each execution of getopts, the next command-line option value
is placed in variable name for processing. Each execution also bumps the OPTIND
counter by one. Using OPTIND allows other command-line options to be
processed after the getopts loop terminates.
|