getopts

NAME

getopts - parse utility options

SYNOPSIS

getopts optstring var [arg ...]

DESCRIPTION

This command is a Korn-shell built-in command.

The getopts(1) command is used by shell procedures to parse the specified arguments (or positional parameters, if no arguments are given) and to check for legal options. The argument optstring contains the option letters that getopts is to recognize. If a letter is followed by a colon, the option is expected to have an argument.

Arguments containing options must all start with either a - or a +; options that do not take arguments can be grouped in a single argument. If an option takes an argument, and the option character is not the last character of the argument in which it is found, the remainder of the argument is taken to be the option's argument; otherwise, the next argument is the option's argument.

Each time getopts is invoked, it places the next option in the shell parameter name and the index of the next argument to be processed in the shell parameter Optind. If the option was introduced with a +, the option placed in name is prefixed with a +. When an option requires an argument, getopts places it in the shell parameter Optarg. When an illegal option or a missing option argument is encountered, a question mark or a colon is placed in name (indicating an illegal option or missing argument, respectively), and Optarg is set to the option character that caused the problem. An error message is also printed to standard error if optstring does not begin with a colon.

When the end of the options is encountered, getopts exits with a non-zero exit status. Options end at the first (non-option argument) argument that does not start with a -, or when a -- argument is encountered.

Option parsing can be reset by setting Optind to 1 (this is done automatically whenever the shell or a shell procedure is invoked).

Important

DIAGNOSTICS

The getopts(1) command returns a non-zero value when it encounters the end of the options.

EXAMPLE

If this shell script is called with the -x option, it displays usage information. If the -b option is given, the script displays -b specified.If the -o option is specified with an argument, the shell script displays -o argument specified. It then displays any additional arguments on separate lines.

CMD=$(basename $0)
USAGE="usage: $CMD [-bx] [-o argument] arg ..."
while getopts bo:x opt
do
		case "$opt" in
		'b') echo "-b specified"
			 ;;
		'o') echo "-o $OPTARG specified"
			 ;;
	 'x') cat <<EndOfHelp
Name
Synopsis:
	$CMD [-bx] [-o argument] arg ..."
Options:
	-x   Print this help
EndOfHelp
			 exit 1;;
		'?') echo $USAGE
			 exit 1;;
		esac
done
shift $OPTIND-1
for arg in $@
do
	 echo $arg
done

SEE ALSO

sh(1)