Getopt
is a C [POSIX library|POSIX C] function used to parse command-line options of the Unix/POSIX style on C. 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 in shell scripts.
History
A long-standing issue with command line programs was how to specify options; early programs used many ways of doing so, including single character options, multiple options specified together, multicharacter options, options with arguments, and different prefix characters.The function was written to be a standard mechanism that all programs could use to parse command-line options so that there would be a common interface on which everyone could depend. As such, the original authors picked out of the variations support for single character options,
multiple options specified together, and options with arguments, all controllable by an option string.
dates back to at least 1980 and was first published by AT&T at the 1985 UNIFORUM conference in Dallas, Texas, with the intent for it to be available in the public domain. Versions of it were subsequently picked up by other flavors of Unix. It is specified in the POSIX.2 standard as part of the unistd.h header file. Derivatives of have been created for many programming languages to parse command-line options.
A POSIX-standard companion function to is. It parses a string of comma-separated sub-options. It appeared in 4.4BSD.
Extensions
is a system dependent function, and its behavior depends on the implementation in the C library. Some custom implementations like gnulib are available, however.The conventional handling is that the options end when the first non-option argument is encountered, and that would return -1 to signal that. In the glibc extension, however, options are allowed anywhere for ease of use; implicitly permutes the argument vector so it still leaves the non-options in the end. Since POSIX already has the convention of returning -1 on and skipping it, one can always portably use it as an end-of-options signifier.
A GNU extension, getopt_long, allows parsing of more readable, multicharacter options, which are introduced by two dashes instead of one. The choice of two dashes allows multicharacter options to be differentiated from single character options specified together. The GNU extension also allows an alternative format for options with arguments:
--name=arg. This interface proved popular, and has been taken up by many BSD distributions including FreeBSD as well as Solaris. An alternative way to support long options is seen in Solaris and Korn Shell, but it was not as popular.Another common advanced extension of getopt is resetting the state of argument parsing; this is useful as a replacement of the options-anyware GNU extension, or as a way to "layer" a set of command-line interface with different options at different levels. This is achieved in BSD systems using an variable, and on GNU systems by setting to 0.
Usage
For users
The command-line syntaxes for getopt-based programs is the POSIX-recommended Utility Argument Syntax. In short:- Options are single-character alphanumerics preceded by a
-character. - Options can take an argument, mandatory or optional, or none.
- In order to specify that an option takes an argument, include
:after the option name - When an option takes an argument, this can be in the same token or in the next one. In other words, if
otakes an argument,-ofoois the same as-o foo. - Multiple options can be chained together, as long as the non-last ones are not argument taking. If
aandbtake no arguments whileetakes an optional argument,-abeis the same as-a -b -e, but-beais not the same as-b -e adue to the preceding rule. - All options precede non-option arguments.
--always marks the end of options.
For programmers
The getopt manual from GNU specifies such a usage for :- include
Here the
argc and argv are defined exactly like they are in the C main function prototype; i.e., argc indicates the length of the argv array of C-strings. The optstring contains a specification of what options to look for, and what options to accept arguments. For example, "vf::o:" refers to three options: an argumentless v, an optional-argument f, and a mandatory-argument o. GNU here implements a W extension for long option synonyms.getopt itself returns an int that is either an option char or -1 for end-of-options. The idiom is to use a while-loop to go through options, and to use a switch-case statement to pick and act on options. See the example section of this article.To communicate extra information back to the program, a few global
extern variables are referenced by the program to fetch information from getopt:extern char* optarg;
extern int optind;
extern int opterr;
extern int optopt;
optarg: A pointer to the argument of the current option, if present. Can be used to control where to start parsing.optind: Where getopt is currently looking at in argv.opterr: A boolean switch controlling whether getopt should print error messages.optopt: If an unrecognized option occurs, the value of that unrecognized character.The GNU extension
getopt_long interface is similar, although it belongs to a different header file and takes an extra option for defining the "short" names of long options and some extra controls. If a short name is not defined, getopt will put an index referring to the option structure in the longindex pointer instead.- include
Examples
Using POSIX standard
- include
- include
- include
Using GNU extension ''getopt_long''
- include
- include
- include
int main
In shell
Shell script programmers commonly want to provide a consistent way of providing options. To achieve this goal, they turn to getopts and seek to port it to their own language.The first attempt at porting was the program getopt, implemented by Unix System Laboratories. This version was unable to deal with quoting and shell metacharacters, as it shows no attempts at quoting. It has been inherited to FreeBSD.
In 1986, USL decided that being unsafe around metacharacters and whitespace was no longer acceptable, and they created the builtin getopts command for Unix SVR3 Bourne Shell instead. The advantage of building the command into the shell is that it now has access to the shell's variables, so values could be written safely without quoting. 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.
In 1995,
getopts was included in the Single UNIX Specification version 1 / X/Open Portability Guidelines Issue 4. Now a part of the POSIX Shell standard, getopts have spread far and wide in many other shells trying to be POSIX-compliant.getopt was basically forgotten until util-linux came out with an enhanced version that fixed all of old getopt's problems by escaping. It also supports GNU's long option names. On the other hand, long options have been implemented rarely in the command in other shells, ksh93 being an exception.
In other languages
getopt is a concise description of the common POSIX command argument structure, and it is replicated widely by programmers seeking to provide a similar interface, both to themselves and to the user on the command-line.- C does not ship in the C standard library, it is called on POSIX systems. gnulib and MinGW, as well as some more minimal libraries, can be used to provide the functionality. Alternative interfaces also exist:
- * The library, used by RPM package manager, has the additional advantage of being reentrant.
- * The family of functions in glibc and gnulib provides some more convenience and modularity.
- C++, if on a POSIX system, can call the same as on C.
- * library from Boost offers similar functionality.
- * from POCO C++ Libraries have classes
ApplicationandOptionSetwhich support argument parsing. - * Google has a library called.
- C# and .NET Framework: does not have getopt functionality in its standard library. Third-party implementations are available, such as.
- D has module in the D standard library.
- Go comes with the package, which allows long flag names. The package supports processing closer to the C function. There is also another package providing interface much closer to the original POSIX one.
- Haskell comes with, which is essentially a Haskell port of the GNU getopt library.
- Java has no implementation of getopt in the Java standard library. Several open source libraries exist, including and the class, which is ported from GNU getopt, and Apache Commons CLI.
- Lisp has many different dialects with no common standard library. There are some third party implementations of getopt for some dialects of Lisp. Common Lisp has a prominent third party implementation.
- Free Pascal: has its own implementation as one of its standard units named. It is supported on all platforms.
- Perl programming language has two separate derivatives of getopt in its standard library: and.
- PHP: has a getopt function.
- Python contains a module in its standard library based on C's getopt and GNU extensions. Python's standard library also contains other modules to parse options that are more convenient to use.
- Ruby has an implementation of in its standard library,. Ruby also has modules in its standard library with a more sophisticated and convenient interface. A third party implementation of the original getopt interface is available.
- Rust has no getopt in the Rust standard library. The library offers similar functionality.