MPE/iX Shell and Utilities Reference Manual, Vol 1

getopts(1) MPE/iX Shell and Utilities getopts(1)
When getopts reaches the end of the options, it exits with a status value of 1. It also sets
name to the character ? and sets OPTIND to the index of the first argument after the options.
getopts recognizes the end of the options by any of the following conditions:
an argument that doesn’t start with
the special argument ––, marking the end of options
an error (for example, an unrecognized option letter)
OPTIND and OPTARG are local to the shell script. If you want to export them, you must do so
explicitly. If the script invoking getopts sets OPTIND to 1, it can call getopts again
with a new set of parameters, either the current positional parameters or new arg values.
By default, getopts issues an error message if it finds an unrecognized option or some other
error. If you do not want such messages printed, specify a colon as the first character in
opstring.
EXAMPLE
This is an example of using getopts in a shell script. Compare it to the getopt example.
# Example illustrating use of getopts builtin. This
# shell script would implement the paste command,
# using getopts to process options, if the underlying
# functionality was embedded in hypothetical utilities
# hpaste and vpaste, which perform horizontal and
# vertical pasting respectively.
#
paste=vpaste # default is vertical pasting
seplist=" " # default separator is tab
while getopts d:s o
do case "$o" in
d) seplist="$OPTARG";;
s) paste=hpaste;;
[?]) print >&2 "Usage: $0 [-s] [-d seplist] file ..."
exit 1;;
esac
done
shift $OPTIND-1
# perform actual paste command
$paste -d "$seplist" "$@"
Commands and Utilities 1-257