getopts

{{Short description|Standard UNIX utility for parsing arguments sent from the command-line}}

{{confuse|getopt}}

{{refimprove|date=February 2017}}

{{lowercase}}

{{Infobox software

| name = getopts

| logo =

| screenshot =

| screenshot size =

| caption =

| author =

| developer = Various open-source and commercial developers

| released = {{Start date and age|1986}}

| latest release version =

| latest release date =

| operating system = Unix, Unix-like, IBM i

| genre = Command

| license =

| website =

}}

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt.

The predecessor to {{code|getopts}} was the external program {{code|getopt}} by Unix System Laboratories.

History

The original {{code|getopt}} had several problems: it could not handle whitespace or shell metacharacters in arguments, and there was no ability to disable the output of error messages.

getopts was first introduced in 1986 in the Bourne shell shipped with Unix SVR3. It uses the shell's own variables to track the position of current and argument positions, {{tt|OPTIND}} and {{tt|OPTARG}}, and returns the option name in a shell variable.{{cite web|url=http://www.in-ulm.de/~mascheck/bourne/|title=The Traditional Bourne Shell Family|access-date=2010-12-01|first=Sven|last=Mascheck}} Earlier versions of the Bourne shell did not have getopts.

In 1995, getopts was included in the Single UNIX Specification version 1 / X/Open Portability Guidelines Issue 4.{{cite web |title=getopts |url=https://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html |website=The Open Group (POSIX 2018)}} As a result, getopts is now available in shells including the Bourne shell, KornShell, Almquist shell, Bash and Zsh.{{Cite web|url=https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins|title=Bash Reference Manual}}

The {{Mono|getopts}} command has also been ported to the IBM i operating system.{{cite web |title=IBM System i Version 7.2 Programming Qshell |language=en |author=IBM |website=IBM |author-link=IBM |url=https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_74/rzahz/rzahzpdf.pdf?view=kc |access-date=2020-09-05 }}

The modern usage of {{code|getopt}} was partially revived mainly due to an enhanced implementation in util-linux. This version, based on the BSD {{code|getopt}}, not only fixed the two complaints around the old {{code|getopt}}, but also introduced the capability for parsing GNU-style long options and optional arguments for options, features that {{code|getopts}} lacks.{{Man|1|getopt|ManKier}} The various BSD distributions, however, stuck to the old implementation.{{man|1|getopt|FreeBSD}}

Usage

The usage synopsis of getopt and getopts is similar to its C sibling:

getopt optstring [parameters]

getopts optstring varname [parameters]

  • The optstring part has the same format as the C sibling.
  • The parameters part simply accepts whatever one wants getopt to parse. A common value is all the parameters, {{tt|"$@"}} in POSIX shell.
  • This value exists in getopts but is rarely used, since it can just access the shell's parameters. It is useful with resetting the parser, however.
  • The varname part of getopts names a shell variable to store the option parsed into.

The way one uses the commands however varies a lot:

  • getopt simply returns a flat string containing whitespace-separated tokens representing the "normalized" argument. One then uses a while-loop to parse it natively.
  • getopts is meant to be repeatedly called like the C getopt. When it hits the end of arguments, it returns 1 (shell false).

Enhancements

=In various getopts=

In spring 2004 (Solaris 10 beta development), the libc implementation for {{tt|getopt()}} was enhanced to support long options. As a result, this new feature was also available in the built-in command getopts of the Bourne Shell. This is triggered by parenthesized suffixes in the optstring specifying long aliases.{{cite web |title=getopt(3) |url=https://docs.oracle.com/cd/E36784_01/html/E36874/getopt-3c.html |website=Oracle Solaris 11.2 Information Library}}

KornShell and Zsh both have an extension for long arguments. The former is defined as in Solaris,{{cite web |title=ksh getopts -- parse options from shell script command line |url=https://www.mkssoftware.com/docs/man1/getopts.1.asp |website=www.mkssoftware.com}} while the latter is implemented via a separate {{code|zparseopts}} command.{{Man|1|zshmodules|ManKier}}

KornShell additionally implements optstring extensions for options beginning with {{code|+}} instead of {{code|-}}.

=In Linux getopt=

An alternative to getopts is the Linux enhanced version of getopt, the external command line program.

The Linux enhanced version of getopt has the extra safety of getopts plus more advanced features. It supports long option names (e.g. --help) and the options do not have to appear before all the operands (e.g. command operand1 operand2 -a operand3 -b is permitted by the Linux enhanced version of getopt but does not work with getopts). It also supports escaping metacharacters for shells (like tcsh and POSIX sh) and optional arguments.

=Comparison=

class="wikitable"
{{diagonal split header|Feature|Program}}POSIX getoptsSolaris/ksh getoptsUnix/BSD getoptLinux getopt
style="text-align: justify" | Splits options for easy parsing

| {{Yes}} || {{Yes}} || {{Yes}} || {{Yes}}

style="text-align: justify" | Allows suppressing error messages

| {{Yes}} || {{Yes}} || {{No}} || {{Yes}}

style="text-align: justify" | Safe with whitespace and metacharacters

| {{Yes}} || {{Yes}} || {{No}} || {{Yes}}

style="text-align: justify" | Allows operands to be mixed with options

| {{No}} || {{Yes}} || {{No}} || {{Yes}}

style="text-align: justify" | Supports long options

| {{Maybe|Emulation}} || {{Yes}} || {{No}} || {{Yes}}

style="text-align: justify" | Optional arguments

| {{Maybe|Error handling}} || {{Maybe|Error handling}} || {{No}} || {{Yes}}

Examples

Suppose we are building a Wikipedia downloader in bash that takes three options and zero extra arguments:

wpdown -a article name -l [language] -v

When possible, we allow the following long arguments:

-a --article

-l --language, --lang

-v --verbose

For clarity, no help text is included, and we assume there is a program that downloads any webpage. In addition, all programs are of the form:

  1. !/bin/bash

verbose=0

article=

lang=en

  1. [EXAMPLE HERE]

if ((verbose > 2)); then

printf '%s\n' 'Non-option arguments:'

printf '%q ' "${remaining[@]]}"

fi

if ((verbose > 1)); then

printf 'Downloading %s:%s\n' "$lang" "$article"

fi

if ! $article ; then

printf '%s\n' "No articles!" >&2

exit 1

fi

save_webpage "https://${lang}.wikipedia.org/wiki/${article}"

=Using old getopt=

The old getopt does not support optional arguments:

  1. parse everything; if it fails we bail

args=`getopt 'a:l:v' $*` || exit

  1. now we have the sanitized args... replace the original with it

set -- $args

while true; do

case $1 in

(-v) ((verbose++)); shift;;

(-a) article=$2; shift 2;;

(-l) lang=$2; shift 2;;

(--) shift; break;;

(*) exit 1;; # error

esac

done

remaining=("$@")

This script will also break with any article title with a space or a shell metacharacter (like ? or *) in it.

=Using getopts=

Getopts give the script the look and feel of the C interface, although in POSIX optional arguments are still absent:

  1. !/bin/sh

while getopts ':a:l:v' opt; do

case $opt in

(v) ((verbose++));;

(a) article=$OPTARG;;

(l) lang=$OPTARG;;

(:) # "optional arguments" (missing option-argument handling)

case $OPTARG in

(a) exit 1;; # error, according to our syntax

(l) :;; # acceptable but does nothing

esac;;

esac

done

shift "$((OPTIND - 1))"

  1. remaining is "$@"

Since we are no longer operating on shell options directly, we no longer need to shift them within the loop. However, a slicing operation is required to remove the parsed options and leave the remaining arguments.

It is fairly simple to emulate long option support of flags by treating {{code|--fast}} as an argument {{code|fast}} to an option {{code|-}}. That is, {{code|-:}} is added to the optstring, and {{code|-}} is added as a case for {{code|opt}}, within which {{code|OPTARG}} is evaluated for a match to {{code|fast}}. Supporting long options with an argument is more tedious, but is possible when the options and arguments are delineated by {{tt|1==}}.{{Cite web|url=https://gist.github.com/webb/ff380b0eee96dafe1c20c2a136d85ef0|title = A simple CLI parser in Bash}}

=Using Linux getopt=

Linux getopt escapes its output and an "eval" command is needed to have the shell interpret it. The rest is unchanged:

  1. !/bin/bash
  1. We use "${@}" instead of "${*}" to preserve argument-boundary information

args=$(getopt --options 'a:l::v' --longoptions 'article:,lang::,language::,verbose' -- "${@}") || exit

eval "set -- ${args}"

while true; do

case "${1}" in

(-v | --verbose)

((verbose++))

shift

;;

(-a | --article)

article=${2}

shift 2

;;

(-l | --lang | --language)

# handle optional: getopt normalizes it into an empty string

if -n ${2} ; then

lang=${2}

fi

shift 2

;;

(--)

shift

break

;;

(*)

exit 1 # error

;;

esac

done

remaining_args=("${@}")

See also

References

{{Reflist}}