GETOPTS(1) BSD Reference Manual GETOPTS(1)NAMEgetopts - POSIX option parsing
SYNOPSISgetopts optstring name [args...]
DESCRIPTION
The getopts shell builtin implements POSIX 1003.2 option parsing, compat-
ible with getopt(3). Options are obtained by examining args, or the po-
sitional parameters if no arguments are provided. As with getotpt(3),
optstring is examined for letters, indicating boolean options, and for
letters followed by colons, indicating options taking an argument.
Each invocation of getopts stores a result (the option, when no error oc-
curs) in the shell variable name, stores the number of the next argument
to be processed in the shell variable OPTIND, and, if an option taking an
argument was found, stores the argument in the shell variable OPTARG.
If an invalid option is found, a question-mark (?) is stored in name,
and, if the first character of optstring was a colon, the character found
is stored in OPTARG.
ENVIRONMENT
Normally, getopts does not modify the environment, however, the shell
variables it modifies can be exported.
The variables set by getopts are:
OPTARG When an option is returned, if it takes an argument, the argument
is stored in OPTARG. OPTARG is not cleared when options without
arguments are parsed, or when errors occur in parsing.
OPTIND The index of the last argument processed by getopts. Setting this
to 1 causes getopts to process arguments from the beginning.
EXAMPLES
A simple shell program to process arguments might look like this:
#!/bin/sh
while getopts ab: o
do
case $o in
a) aflag="Y";;
b) bvar="$OPTARG";;
\?) echo >&2 "usage: cmd [-a] [-b bval] [file ...]"
exit 1
;;
esac
done
shift $(expr $OPTIND - 1)
# now $* contains all the arguments not processed by getopt.
The shell itself will diagnose options taking arguments for which no ar-
guments are provided.
STANDARDS
The getopts shell builtin is expected to conform to the IEEE Std1003.2
(``POSIX'') standard. Conformance may vary from shell to shell; see spe-
cific shell manuals for details.
BUGS
There may be slight variance between the way that different shells imple-
ment getopts. The csh(1) shell and its derivatives do not support
getopts.
SEE ALSOgetopt(3), sh(1), ksh(1), bash(1)BSDI BSD/OS August 23, 1999 2