Processes command-line arguments and checks for valid options.
getopts OptionString Name [Argument ...]
The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString. Each time the getopts command is invoked, it places the value of the next option in Name and the index of the next argument to be processed in the shell variable OPTIND. Whenever the shell is invoked, OPTIND is intialized to 1. When an option begins with +, a + is prepended to the value in Name.
If a character in OptionString is followed by a : (colon), that option is expected to have an argument. When an option requires an option-argument, the getopts command places it in the variable OPTARG.
When an option character not contained in OptionString is found, or an option found does not have the required option-argument:
This condition is considered to be an error detected in the way arguments were presented to the invoking application, but is not an error in the processing of the getopts command; a diagnostic message will be written as stated, but the exit status will be zero.
Any of the following identifies the end of options: the special option - -, finding an argument that does not begin with a -, or +, or encountering an error.
When the end of options is encountered:
|OptionString||Contains the string of option characters recognized by the getopts command. If a character is followed by a colon, that option is expected to have an argument, which should be supplied as a separate argument. The options can be separated from the argument by blanks. The first character in OptionString determines how the getopts command behaves if an option character is not known or an option-argument is missing.|
|Name||Set by the getopts command to the option character that was found.|
|Argument ...||One or more strings separted by white space, checked by the getopts command for legal options. If Argument is omitted, the positional parameters are used. See Parameter Substitution in the Korn Shell for more information on positional parameters.|
This command returns the following exit values:
|0||An optiong, specified or unspecified by OptionString, was found.|
|>0||The end of options was encountered or an error occured.|
getopts a:bc: OPT
getopts :a:b:c OPT
aflag= bflag= while getopts ab: name do case $name in a) aflag=1;; b) bflag=1 bval="$OPTARG";; ?) printf "Usage: %s: [-a] [-b value] args\n" $0 exit 2;; esac done if [ ! -z "$aflag" ]; then printf "Option -a specified\n" fi if [ ! -z "$bflag" ]; then printf 'Option -b "%s" specified\n' "$bval" fi shift $(($OPTIND -1)) printf "Remaining arguments are: %s\n" "$*"
Korn Shell in AIX Version 4.3 System User's Guide: Operating System and Devices.