HP-UX Reference (11i v2 07/12) - 1 User Commands A-M (vol 1)
g
getopts(1) getopts(1)
getopts by default parses positional parameters passed to the invoking shell procedures. If args are
given, they are parsed instead of the positional parameters.
EXTERNAL INFLUENCES
Environment Variable
The following environment variable affects the execution of the
getopts utility:
OPTIND Used by getopts as the index of the next argument to be processed.
ERRORS
Whenever an error is detected and the first character in the optstring operand is not a colon (
:), a diagnos-
tic message will be written to standard error with the following information in an unspecified format:
• The invoking program name will be identified in the message. The invoking program name will be
the value of the shell special parameter 0 at the time the
getopts utility is invoked. A name
equivalent to:
basename "$0"
may be used.
• If an option is found that was not specified in optstring, this error will be identified and the invalid
option character will be identified in the message.
• If an option requiring an option-argument is found, but an option-argument is not found, this error
will be identified and the invalid option character will be identified in the message.
EXAMPLES
Since
getopts affects the current shell execution environment, it is generally provided as a shell regular
built-in. If it is called in a subshell or separate utility execution environment such as one of the following:
(getopts abc value "$@")
nohup getopts ...
find -exec getopts ...\;
it does not affect the shell variables in the caller’s environment.
Note that shell functions share OPTIND with the calling shell even though the positional parameters are
changed. Functions that use getopts to parse their arguments should save the value of
OPTIND on
entry and restore it before returning. However, there will be cases when a function must change
OPTIND
for the calling shell.
The following example script parses and displays its arguments:
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" "$*"
404 Hewlett-Packard Company − 2 − HP-UX 11i Version 2: December 2007 Update