getopt

From Wikipedia, the free encyclopedia
Jump to: navigation, search

getopt is a C library function used to parse command-line options.

It is also the name of a Unix program for parsing command line arguments in shell scripts.

History[edit]

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 getopt 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 that everyone could depend on. 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.

getopt 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.[citation needed] Versions of it were subsequently picked up by other flavors of Unix (BSD 4.3, GNU/Linux, etc.). It is specified in the POSIX.2 standard as part of the unistd.h header file. Derivatives of getopt have been created for many programming languages to parse command-line options.

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.

getopt is a system dependent function. The implementation of getopt in GNU C Library does permute the contents of the argument vector as it scans, so that eventually all the non-option arguments are at the end. On the contrary, the implementation of getopt in BSD C Library does not permute the argument vector and returns -1 if it encounters a non-option argument.

Example 1 (using POSIX standard getopt)[edit]

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <unistd.h>    /* for getopt */
int main (int argc, char **argv) {
    int c;
    int digit_optind = 0;
    int aopt = 0, bopt = 0;
    char *copt = 0, *dopt = 0;
    while ( (c = getopt(argc, argv, "abc:d:012")) != -1) {
        int this_option_optind = optind ? optind : 1;
        switch (c) {
        case '0':
        case '1':
        case '2':
            if (digit_optind != 0 && digit_optind != this_option_optind)
              printf ("digits occur in two different argv-elements.\n");
            digit_optind = this_option_optind;
            printf ("option %c\n", c);
            break;
        case 'a':
            printf ("option a\n");
            aopt = 1;
            break;
        case 'b':
            printf ("option b\n");
            bopt = 1;
            break;
        case 'c':
            printf ("option c with value '%s'\n", optarg);
            copt = optarg;
            break;
        case 'd':
            printf ("option d with value '%s'\n", optarg);
            dopt = optarg;
            break;
        case '?':
            break;
        default:
            printf ("?? getopt returned character code 0%o ??\n", c);
        }
    }
    if (optind < argc) {
        printf ("non-option ARGV-elements: ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }
    exit (0);
}

Example 2 (using GNU extension getopt_long)[edit]

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <getopt.h>    /* for getopt_long; POSIX standard getopt is in unistd.h */
int main (int argc, char **argv) {
    int c;
    int digit_optind = 0;
    int aopt = 0, bopt = 0;
    char *copt = 0, *dopt = 0;
    static struct option long_options[] = {
        {"add", 1, 0, 0},
        {"append", 0, 0, 0},
        {"delete", 1, 0, 0},
        {"verbose", 0, 0, 0},
        {"create", 1, 0, 'c'},
        {"file", 1, 0, 0},
        {NULL, 0, NULL, 0}
    };
    int option_index = 0;
    while ((c = getopt_long(argc, argv, "abc:d:012",
                 long_options, &option_index)) != -1) {
        int this_option_optind = optind ? optind : 1;
        switch (c) {
        case 0:
            printf ("option %s", long_options[option_index].name);
            if (optarg)
                printf (" with arg %s", optarg);
            printf ("\n");
            break;
        case '0':
        case '1':
        case '2':
            if (digit_optind != 0 && digit_optind != this_option_optind)
              printf ("digits occur in two different argv-elements.\n");
            digit_optind = this_option_optind;
            printf ("option %c\n", c);
            break;
        case 'a':
            printf ("option a\n");
            aopt = 1;
            break;
        case 'b':
            printf ("option b\n");
            bopt = 1;
            break;
        case 'c':
            printf ("option c with value '%s'\n", optarg);
            copt = optarg;
            break;
        case 'd':
            printf ("option d with value '%s'\n", optarg);
            dopt = optarg;
            break;
        case '?':
            break;
        default:
            printf ("?? getopt returned character code 0%o ??\n", c);
        }
    }
    if (optind < argc) {
        printf ("non-option ARGV-elements: ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }
    exit (0);
}

Other languages[edit]

Shell[edit]

The Unix shell command program called getopt can be used for parsing command line arguments in shell scripts.

There are two major versions of the getopt shell command program. The original version was implemented by Unix System Laboratories. Most Linux based operating systems come with an enhanced version that supports additional features (such as long option names).

Command line parsing in shell scripts can also be performed using the getopts command, also designed and implemented by Unix System Laboratories as a replacement for getopt. This version is available as a built-in in many shells and standardized by POSIX (contrary to getopt). The syntax for using getopts is very different from the syntax of getopt. Although getopts has more features than the original getopt program, its implementation as specified by POSIX does not have some of the features of the Linux enhanced version of getopt (though some implementations like ksh93's do). For example, implementations of getopts other than ksh93's do not support long option names. The getopts command is a built-in Unix shell command, unlike getopt (either the original version or the Linux enhanced version) which is an external command line program. Being a built-in Unix shell command allows it to interact more seamlessly with other built-in shell options and variables.

D[edit]

The D programming language has a getopt module in the standard library.

Haskell[edit]

Haskell comes with System.Console. GetOpt in the base library which is essentially a Haskell port of the GNU getopt library.[2]

Java[edit]

There is no implementation of getopt in the Java standard library. Several open source modules exist, including gnu.getopt.Getopt, which is ported from GNU getopt,[3] and Apache Commons CLI.[4]

Lisp[edit]

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.

Pascal[edit]

Free Pascal has its own implementation as one of its standard units named GetOpts. It is supported on all platforms.

Perl[edit]

The Perl programming language has two separate derivatives of getopt in its standard library: Getopt::Long[5] and Getopt::Std.[6]

PHP[edit]

PHP has a getopt() function.[7]

Python[edit]

Python contains a module in its standard library based on C's getopt and GNU extensions.[8] Python's standard library also contains other modules to parse options that are more convenient to use.[9][10]

Ruby[edit]

Ruby has an implementation of getopt_long in its standard library, GetoptLong. 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.

.NET Framework[edit]

The .NET Framework does not have getopt functionality in its standard library. Third-party implementations are available.[11]

See also[edit]

References[edit]

  1. ^ ftp://pdp11.org.ru/pub/unix-archive/PDP-11/Distributions/usdl/SysIII/
  2. ^ Haskell Documentation: System.Console.GetOpt
  3. ^ "Class gnu.getopt.Getopt". Retrieved 2013-06-24. 
  4. ^ "Commons CLI". Apache Commons. Apache Software Foundation. February 27, 2013. Retrieved June 24, 2013. 
  5. ^ Perl Doc for Getopt::Long
  6. ^ Perl Doc for Getopt::Std
  7. ^ http://www.php.net/manual/en/function.getopt.php
  8. ^ http://docs.python.org/library/getopt.html
  9. ^ "Parser for command line options". Retrieved 2013-04-30.  Deprecated since version 2.7
  10. ^ "Parser for command-line options, arguments and sub-commands". Retrieved 2013-04-30. 
  11. ^ http://www.codeplex.com/getopt

External links[edit]