Getopts
   HOME

TheInfoList



OR:

getopts is a
built-in Built-in, builtin, or built in may refer to: Computing * Shell builtin, a command or a function executed directly in the shell itself * Builtin function, in computer software and compiler theory Other uses * Built-in behavior, of a living orga ...
Unix shell A Unix shell is a command-line interpreter or shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting language, and is used by the operating system t ...
command for parsing
command-line argument A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
s. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of
getopt Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments ...
. The predecessor to was the external program by
Unix System Laboratories Unix System Laboratories (USL), sometimes written UNIX System Laboratories to follow relevant trademark guidelines of the time, was an American software laboratory and product development company that existed from 1989 through 1993. At first wh ...
.


History

The original 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 The Bourne shell (sh) is a shell command-line interpreter for computer operating systems. The Bourne shell was the default shell for Version 7 Unix. Unix-like systems continue to have /bin/sh—which will be the Bourne shell, or a symbolic link ...
shipped with Unix SVR3. It uses the shell's own variables to track the position of current and argument positions, and , and returns the option name in a shell variable. Earlier versions of the Bourne shell did not have ''getopts''. In 1995, getopts was included in the Single UNIX Specification version 1 /
X/Open X/Open group (also known as the Open Group for Unix Systems and incorporated in 1987 as X/Open Company, Ltd.) was a consortium founded by several European UNIX systems manufacturers in 1984 to identify and promote open standards in the field of in ...
Portability Guidelines Issue 4. As a result, getopts is now available in shells including the
Bourne shell The Bourne shell (sh) is a shell command-line interpreter for computer operating systems. The Bourne shell was the default shell for Version 7 Unix. Unix-like systems continue to have /bin/sh—which will be the Bourne shell, or a symbolic link ...
,
KornShell KornShell (ksh) is a Unix shell which was developed by David Korn at Bell Labs in the early 1980s and announced at USENIX on July 14, 1983. The initial development was based on Bourne shell source code. Other early contributors were Bell ...
,
Almquist shell Almquist shell (also known as A Shell, ash and sh) is a lightweight Unix shell originally written by Kenneth Almquist in the late 1980s. Initially a clone of the System V.4 variant of the Bourne shell, it replaced the original Bourne shell in th ...
, Bash and
Zsh The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell and as a command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including some features of Bash, ksh, and tcsh. Hist ...
. The command has also been ported to the
IBM i IBM i (the ''i'' standing for ''integrated'') is an operating system developed by IBM for IBM Power Systems. It was originally released in 1988 as OS/400, as the sole operating system of the IBM AS/400 line of systems. It was renamed to i5/OS i ...
operating system. The modern usage of was partially revived mainly due to an enhanced implementation in
util-linux is a standard package distributed by the Linux Kernel Organization for use as part of the Linux operating system. A fork, (with meaning "next generation"), was created when development stalled, but has been renamed back to , and is the off ...
. This version, based on the BSD , not only fixed the two complaints around the old , but also introduced the capability for parsing GNU-style long options and optional arguments for options, features that lacks. The various BSD distributions, however, stuck to the old implementation.


Usage

The usage synopsis of getopt and getopts is similar to its C sibling: getopt ''optstring'' '' arameters' getopts ''optstring'' ''varname'' '' arameters' * 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, 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 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.
KornShell KornShell (ksh) is a Unix shell which was developed by David Korn at Bell Labs in the early 1980s and announced at USENIX on July 14, 1983. The initial development was based on Bourne shell source code. Other early contributors were Bell ...
and
Zsh The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell and as a command interpreter for shell scripting. Zsh is an extended Bourne shell with many improvements, including some features of Bash, ksh, and tcsh. Hist ...
both have an extension for long arguments. The former is defined as in Solaris, while the latter is implemented via a separate command. KornShell additionally implements ''optstring'' extensions for options beginning with instead of .


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 tcsh ( “tee-see-shell”, “tee-shell”, or as “tee see ess aitch”, tcsh) is a Unix shell based on and backward compatible with the C shell (csh). Shell It is essentially the C shell with programmable command-line completion, comman ...
and POSIX sh) and optional arguments.


Comparison


Examples

Suppose we are building a Wikipedia downloader in bash that takes three options and zero extra arguments: wpdown -a ''article name'' -l '' anguage' -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: #!/bin/bash VERBOSE=0 ARTICLE='' LANG=en #
XAMPLE HERE Gavin Harris, better known as Xample, is a British drum and bass producer and DJ, who originates from Bristol, England. He has been releasing records since 2003. In June 2007, he scored a number 1 on the UK Dance Chart The UK Dance Singles C ...
if ((VERBOSE > 2)); then printf '%s\n' 'Non-option arguments:' printf '%q ' "$" 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://$.wikipedia.org/wiki/$"


Using old getopt

The old getopt does not support optional arguments: # parse everything; if it fails we bail args=`getopt 'a:l:v' $*` , , exit # 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: #!/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" # remaining is "$@" Since we are no longer operating on shell options directly, we no longer need to shift them. However, a slicing operating is required to get the remaining arguments now. It is possible, but tedious to emulate long argument support by treating as an argument to an option .


Using Linux getopt

Linux getopt escapes its output and an "eval" command is needed to have the shell interpret it. The rest is unchanged: # We use "$@" instead of $* to preserve argument-boundary information ARGS=$(getopt -o 'a:l::v' --long 'article:,language::,lang::,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=("$@")


See also

*
List of Unix commands This is a list of Unix commands as specified by IEEE Std 1003.1-2008, which is part of the Single UNIX Specification (SUS). These commands can be found on Unix operating systems and most Unix-like operating systems. List See also * List of G ...


References


External links

* Unix SUS2008 utilities IBM i Qshell commands {{unix-stub