Open System Services Shell and Utilities Reference Manual (G06.28+, H06.05+)

getopts(1) OSS Shell and Utilities Reference Manual
NAME
getopts - Parses command options
SYNOPSIS
getopts optstring name [argument ...]
DESCRIPTION
The getopts command checks a specied command for legal options.
Operands
optstring Species the letters that the getopts command will recognize as valid option
values when parsing the command options. If a letter is followed by a : (colon),
the option is expected to have an argument specied in argument. The options
can be separated from the argument by spaces.
name Species the name of a shell environment variable into which the getopts com-
mand should place the value of the next option.
argument Species an option argument for the getopts command to parse. If argument is
omitted, positional parameters are parsed.
An option argument begins with a + (plus sign) or a - (dash). Either an option
not beginning with + or - or the argument -- ends the options.
Each time it is invoked, getopts places the next option letter it nds into the vari-
able name. The value stored has a + added in front when argument begins with a
+.
The index of the next argument is stored in OPTIND. OPTIND is initialized to
1 when the shell is invoked.
The option argument, if any, gets stored in OPTARG.
If a required option argument is missing, a leading : in optstring causes getopts
to store the letter of an invalid option in OPTARG and to set name to : (colon).
Otherwise, name is set to a ? (question mark), the shell variable OPTARG is not
set, and getopts prints an error message. The exit status remains 0 (zero).
The exit status is nonzero when there are no more options.
Environment Variables
This command supports the use of the LANG, LC_ALL, LC_CTYPE, LC_MESSAGES,
NLSPATH, OPTARG, and OPTIND environment variables.
EXAMPLES
The following section from a shell script takes the command line passed from the invoking pro-
cess and extracts the ag characters. There are two expected ags: the -a ag and the -b ag.
The -b ag requires an argument. At the end, the script echoes the remaining arguments not
extracted by the getopts command.
aag=
bag=
while getopts ab: name
do
case $name in
a) aag=1
b) bag=1
bval-"$OPTARG";;
?) echo Usage: $0 [-a] [-b value] parameters
exit 2;;
esac
420 Hewlett-Packard Company 527188-007