Automating frequent tasks

Getting options from the command line: getopts

Lines 77 to 98 of our example script illustrate a very important feature of any batch script: how to read parameters from a command line. Both the Bourne and Korn shells provide a built in command called getopts to read command line parameters. (Note that this should not be confused with the earlier, and obsolete, command getopt, which is inferior and should not be used.)

For example, we might want our program to respond to any of the following:

prog -h
prog -H
prog -v
prog -f filename

To handle command line options, we need a means of distinguishing between parameters that are filenames, and parameters that are flags.

To use getopts, first establish the various flags the program is to understand. For example, for the above syntax, the options are hHvf:. The colon after the ``f'' indicates that the ``f'' is to be followed by an additional parameter (such as a filename).

For example:

   79	:	while getopts "hHvlbf:" result
   80	:	do
   81	:	  case $result in
Each time the while loop runs, getopts is invoked, scans the parameters to the script, and places the first new option it finds in a special variable called result. The index number of the next shell argument to process is placed in another special variable called OPTIND, and if the flag has an optional argument (like the f: option above) the argument is placed in OPTARG. If getopts cannot find an option, it exits with a non-zero (or failure) exit value.

It is up to the shell script to retrieve all the options from a parameter list. So optargs is usually used in a structure called a while loop, explained below.

Next topic: Repeating commands zero or more times: the while loop
Previous topic: Making a command repeat: the for loop

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005