Getopt
≈ 8 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
is a 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.
is a 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. 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 and was first published by AT&T at the 19851 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 (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 is . It parses a string of comma-separated sub-options. It appeared in 4.4BSD (1995). 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 . 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. 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. include int getopt(int argc, char* const argv[], const char* optstring); 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 (normal alphanumerals except W ), and what options to accept arguments (colons). 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 (again). 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 int getopt_long(int argc, char* const argv[], const char* optstring, const struct option* longopts, int* longindex); include include include int main(int argc, char* argv[]) { int c; int digit_optind = 0; int opt_a = 0; int opt_b = 0; char* opt_c = NULL; char* opt_d = NULL; while ((c = getopt(argc, argv, "abc:d:012")) != -1) { int this_option_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"); opt_a = 1; break; case 'b': printf("option b\n"); opt_b = 1; break; case 'c': printf("option c with value '%s'\n", optarg); opt_c = optarg; break; case 'd': printf("option d with value '%s'\n", optarg); opt_d = optarg; break; case '?': break; default: printf("?? getopt returned character code 0%o ??\n", c); } } if (optind include include include typedef struct option Option; int main(int argc, char* argv[]) { int c; int digit_optind = 0; int aopt = 0; int bopt = 0; char* copt = 0; char* dopt = 0; // Option layout: Name, Argument, Flag, Short name static Option long_options[] = { {"add", required_argument, NULL, 0}, {"append", no_argument, NULL, 0}, {"delete", required_argument, NULL, 0}, {"verbose", no_argument, NULL, 0}, {"create", required_argument, NULL, 'c'}, {"file", required_argument, NULL, 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 ==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 (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. 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.
Text derived from https://en.wikipedia.org/w/index.php?oldid=1366746038 under CC BY-SA 4.0; modifications have been made.