getopts opstring name [arg …]
getopts obtains options and their arguments from a list of parameters that follows the standard POSIX.2POSIX.2 option syntax (that is, single letters preceded by a hyphen (–) and possibly followed by an argument value). Typically, shell scripts use getopts to parse arguments passed to them. When you specify arguments with the arg argument on the getopts command line, getopts parses those arguments instead of the script command-line arguments (see set).
getopts places a question mark (?) in name if it finds an option that does not appear in opstring, or if an option value is missing.
When an option letter has a following argument (indicated with a : in opstring), getopts stores the argument as a string in the shell variable OPTARG. If an option doesn't take an argument, or if getopts expects an argument but doesn't find one, getopts unsets OPTARG.
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 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" "$@"
See Localization for more information.
getopts is a built-in shell command.
POSIX.2, X/Open Portability Guide.
On UNIX systems, getopts is built in both the KornShell and Bourne shell.
sh