Getopt Explained

Getopt should not be confused with getopts.

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 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 (-a), multiple options specified together (-abc is equivalent to -a -b -c), multicharacter options (-inum), options with arguments (-a arg, -inum 3, -a=arg), and different prefix characters (-a, +b, /c).

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 (-a arg or -aarg), all controllable by an option string.

dates back to at least 1980[1] 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.[2] Versions of it were subsequently picked up by other flavors of Unix (4.3BSD, Linux, etc.). 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 [3] is .[4] It parses a string of comma-separated sub-options. It appeared in 4.4BSD (1995).

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 (POSIX and BSD) 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.[5]

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 (--inum) to be differentiated from single character options specified together (-abc). The GNU extension also allows an alternative format for options with arguments: --name=arg.[5] This interface proved popular, and has been taken up (sans the permutation) by many BSD distributions including FreeBSD as well as Solaris. An alternative way to support long options is seen in Solaris and Korn Shell (extending optstring), but it was not as popular.[6]

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.[5]

Usage

For users

The command-line syntaxes for getopt-based programs is the POSIX-recommended Utility Argument Syntax. In short:[7]

Extensions on the syntax include the GNU convention and Sun's specification.[8] [9]

For programmers

The getopt manual from GNU specifies such a usage for getopt:

  1. include

int getopt(int argc, char * const argv[], const char *optstring);Here the and are defined exactly like they are in the C function prototype; i.e., argc indicates the length of the argv array-of-strings. The contains a specification of what options to look for (normal alphanumerals except), and what options to accept arguments (colons). For example, refers to three options: an argumentless, an optional-argument, and a mandatory-argument . GNU here implements a extension for long option synonyms.

itself returns an integer that is either an option character 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 variables are referenced by the program to fetch information from :extern char *optarg;extern int optind, opterr, optopt;

optarg: A pointer to the argument of the current option, if present. Can be used to control where to start parsing (again).
  • optind: Where getopt is currently looking at in .
  • 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 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 pointer instead.

    1. include

    int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);

    Examples

    Using POSIX standard getopt

    1. include /* for printf */
    2. include /* for exit */
    3. include /* for getopt */

    int main (int argc, char **argv)

    Using GNU extension getopt_long

    1. include /* for printf */
    2. include /* for exit */
    3. include /* for getopt_long; POSIX standard getopt is in unistd.h */

    int main (int argc, char **argv)

    In Shell

    See main article: getopts. 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 (USL). 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.[10] 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.

    External links

    Notes and References

    1. Web site: usr/src/lib/libc/pdp11/gen/getopt.c . live . From System III, released June 1980, linked here from Warren Toomey's The Unix Tree project . 2024-04-22 . https://web.archive.org/web/20230512145228/https://www.tuhs.org/cgi-bin/utree.pl?file=SysIII/usr/src/lib/libc/pdp11/gen/getopt.c . 2023-05-12.
    2. Web site: Quarterman . John . public domain AT&T getopt source . linux.co.cr (originally in mod.std.unix newsgroup) . live . 1985-11-03 . 2024-04-22 . https://web.archive.org/web/20230512145228/https://www.linux.co.cr/unix-source-code/review/1985/1103.html . 2023-05-12.
    3. Web site: The Open Group Base Specifications Issue 7, 2018 edition; IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008) . getopt . live . . 2018 . 2024-04-22 . https://web.archive.org/web/20240324185041/https://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html#tag_16_206 . 2024-03-24.
    4. Web site: The Open Group Base Specifications Issue 7, 2018 edition; IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008) . getsubopt . live . . 2018 . 2024-04-22 . https://web.archive.org/web/20231202013444/https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsubopt.html#tag_16_221 . 2023-12-02.
    5. Web site: getopt . GNU Gnulib . 23 January 2020.
    6. Web site: getopt(3) . Oracle Solaris 11.2 Information Library.
    7. Web site: Utility Conventions . POSIX.1-2018 .
    8. Web site: Argument Syntax . The GNU C Library . 24 January 2020.
    9. Web site: David-John . Burrowes . Kowalski III . Joseph E. . CLIP Specification, Version 1.0, PSARC 1999/645 . deviated . 2003-01-22 . https://web.archive.org/web/20200627031620/http://www.logicoy.com/wikilogicoy/attach/GeneralUsageInformation/clip.pdf . 2020-06-27.
    10. Web site: getopts . The Open Group (POSIX 2018).
    11. Web site: visual studio - getopt.h: Compiling Linux C-Code in Windows . Stack Overflow .
    12. Web site: Package flag .
    13. Web site: Package getopt .
    14. Web site: Package getopt .
    15. Web site: System.Console.GetOpt .
    16. Web site: Class gnu.getopt.Getopt . 2013-06-24.
    17. Web site: February 27, 2013 . Commons CLI . Apache Software Foundation . Apache Commons . June 24, 2013.
    18. Web site: Getopt::Long - perldoc.perl.org.
    19. Web site: Getopt::Std - perldoc.perl.org.
    20. Web site: PHP: getopt - Manual .
    21. Web site: 16.5. getopt — C-style parser for command line options — Python 3.6.0 documentation .
    22. Web site: Parser for command line options . 2013-04-30. Deprecated since version 2.7
    23. Web site: Parser for command-line options, arguments and sub-commands . 2013-04-30.
    24. Web site: GNU Getopt .NET . .