Open System Services Shell and Utilities Reference Manual (G06.29+, H06.08+, J06.03+)

getopts(1) OSS Shell and Utilities Reference Manual
NAME
getopts - Parses command options
SYNOPSIS
getopts optstring name [argument ...]
DESCRIPTION
The getopts command checks a specified command for legal options.
Operands
optstring Specifies 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 specified in argument. The options can be
separated from the argument by spaces.
name Specifies the name of a shell environment variable into which
the getopts command should place the value of the next option.
argument Specifies 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
finds into the variable 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, O
PTARG, 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 flag characters. There are two expected flags: the -a flag 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.
aflag=
bflag=
while getopts ab: name
do
case $name in
422 Hewlett-Packard Company 527188-021