2 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
3 .\" and Copyright 2006-2008, Michael Kerrisk <mtk.manpages@gmail.com>
5 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
7 .\" Modified Sat Jul 24 19:27:50 1993 by Rik Faith (faith@cs.unc.edu)
8 .\" Modified Mon Aug 30 22:02:34 1995 by Jim Van Zandt <jrv@vanzandt.mv.com>
9 .\" longindex is a pointer, has_arg can take 3 values, using consistent
10 .\" names for optstring and longindex, "\n" in formats fixed. Documenting
11 .\" opterr and getopt_long_only. Clarified explanations (borrowing heavily
12 .\" from the source code).
13 .\" Modified 8 May 1998 by Joseph S. Myers (jsm28@cam.ac.uk)
14 .\" Modified 990715, aeb: changed `EOF' into `-1' since that is what POSIX
15 .\" says; moreover, EOF is not defined in <unistd.h>.
16 .\" Modified 2002-02-16, joey: added information about nonexistent
17 .\" option character and colon as first option character
18 .\" Modified 2004-07-28, Michael Kerrisk <mtk.manpages@gmail.com>
19 .\" Added text to explain how to order both '[-+]' and ':' at
20 .\" the start of optstring
21 .\" Modified 2006-12-15, mtk, Added getopt() example program.
23 .TH getopt 3 (date) "Linux man-pages (unreleased)"
25 getopt, getopt_long, getopt_long_only,
26 optarg, optind, opterr, optopt \- Parse command-line options
29 .RI ( libc ", " \-lc )
32 .B #include <unistd.h>
34 .BI "int getopt(int " argc ", char *" argv [],
35 .BI " const char *" optstring );
37 .BI "extern char *" optarg ;
38 .BI "extern int " optind ", " opterr ", " optopt ;
40 .B #include <getopt.h>
42 .BI "int getopt_long(int " argc ", char *" argv [],
43 .BI " const char *" optstring ,
44 .BI " const struct option *" longopts ", int *" longindex );
45 .BI "int getopt_long_only(int " argc ", char *" argv [],
46 .BI " const char *" optstring ,
47 .BI " const struct option *" longopts ", int *" longindex );
51 Feature Test Macro Requirements for glibc (see
52 .BR feature_test_macros (7)):
57 _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
61 .BR getopt_long_only ():
68 function parses the command-line arguments.
73 are the argument count and array as passed to the
75 function on program invocation.
76 An element of \fIargv\fP that starts with \[aq]\-\[aq]
77 (and is not exactly "\-" or "\-\-")
79 The characters of this element
80 (aside from the initial \[aq]\-\[aq]) are option characters.
83 is called repeatedly, it returns successively each of the option characters
84 from each of the option elements.
88 is the index of the next element to be processed in
90 The system initializes this value to 1.
91 The caller can reset it to 1 to restart scanning of the same
93 or when scanning a new argument vector.
97 finds another option character, it returns that
98 character, updating the external variable \fIoptind\fP and a static
99 variable \fInextchar\fP so that the next call to
102 resume the scan with the following option character or
105 If there are no more option characters,
108 Then \fIoptind\fP is the index in \fIargv\fP of the first
109 \fIargv\fP-element that is not an option.
112 is a string containing the legitimate option characters.
113 A legitimate option character is any visible one byte
117 would return nonzero) that is not \[aq]\-\[aq], \[aq]:\[aq], or \[aq];\[aq].
119 character is followed by a colon, the option requires an argument, so
121 places a pointer to the following text in the same
122 \fIargv\fP-element, or the text of the following \fIargv\fP-element, in
124 Two colons mean an option takes
125 an optional arg; if there is text in the current \fIargv\fP-element
126 (i.e., in the same word as the option name itself, for example, "\-oarg"),
127 then it is returned in \fIoptarg\fP, otherwise \fIoptarg\fP is set to zero.
128 This is a GNU extension.
133 followed by a semicolon, then
135 is treated as the long option
139 option is reserved by POSIX.2 for implementation extensions.)
140 This behavior is a GNU extension, not available with libraries before
145 permutes the contents of \fIargv\fP as it
146 scans, so that eventually all the nonoptions are at the end.
147 Two other scanning modes are also implemented.
148 If the first character of
149 \fIoptstring\fP is \[aq]+\[aq] or the environment variable
151 is set, then option processing stops as soon as a nonoption argument is
153 If \[aq]+\[aq] is not the first character of
155 it is treated as a normal option.
158 behaviour is required in this case
160 will contain two \[aq]+\[aq] symbols.
161 If the first character of \fIoptstring\fP is \[aq]\-\[aq], then
162 each nonoption \fIargv\fP-element is handled as if it were the argument of
163 an option with character code 1.
164 (This is used by programs that were
165 written to expect options and other \fIargv\fP-elements in any order
166 and that care about the ordering of the two.)
167 The special argument "\-\-" forces an end of option-scanning regardless
168 of the scanning mode.
170 While processing the option list,
172 can detect two kinds of errors:
173 (1) an option character that was not specified in
175 and (2) a missing option argument
176 (i.e., an option at the end of the command line without an expected argument).
177 Such errors are handled and reported as follows:
181 prints an error message on standard error,
182 places the erroneous option character in
184 and returns \[aq]?\[aq] as the function result.
186 If the caller has set the global variable
190 does not print an error message.
191 The caller can determine that there was an error by testing whether
192 the function return value is \[aq]?\[aq].
195 has a nonzero value.)
197 If the first character
198 (following any optional \[aq]+\[aq] or \[aq]\-\[aq] described above)
200 is a colon (\[aq]:\[aq]), then
202 likewise does not print an error message.
203 In addition, it returns \[aq]:\[aq] instead of \[aq]?\[aq] to
204 indicate a missing option argument.
205 This allows the caller to distinguish the two different types of errors.
207 .SS getopt_long() and getopt_long_only()
212 except that it also accepts long options, started with two dashes.
213 (If the program accepts only long options, then
215 should be specified as an empty string (""), not NULL.)
216 Long option names may be abbreviated if the abbreviation is
217 unique or is an exact match for some defined option.
219 may take a parameter, of the form
222 .BR "\-\-arg param" .
225 is a pointer to the first element of an array of
242 The meanings of the different fields are:
245 is the name of the long option.
249 \fBno_argument\fP (or 0) if the option does not take an argument;
250 \fBrequired_argument\fP (or 1) if the option requires an argument; or
251 \fBoptional_argument\fP (or 2) if the option takes an optional argument.
254 specifies how results are returned for a long option.
259 (For example, the calling program may set \fIval\fP to the equivalent short
264 \fIflag\fP points to a variable which is set to \fIval\fP if the
265 option is found, but left unchanged if the option is not found.
268 is the value to return, or to load into the variable pointed
271 The last element of the array has to be filled with zeros.
273 If \fIlongindex\fP is not NULL, it
274 points to a variable which is set to the index of the long option relative to
277 .BR getopt_long_only ()
280 but \[aq]\-\[aq] as well
281 as "\-\-" can indicate a long option.
282 If an option that starts with \[aq]\-\[aq]
283 (not "\-\-") doesn't match a long option, but does match a short option,
284 it is parsed as a short option instead.
286 If an option was successfully found, then
288 returns the option character.
289 If all command-line options have been parsed, then
294 encounters an option character that was not in
296 then \[aq]?\[aq] is returned.
299 encounters an option with a missing argument,
300 then the return value depends on the first character in
302 if it is \[aq]:\[aq], then \[aq]:\[aq] is returned;
303 otherwise \[aq]?\[aq] is returned.
307 .BR getopt_long_only ()
308 also return the option
309 character when a short option is recognized.
310 For a long option, they
311 return \fIval\fP if \fIflag\fP is NULL, and 0 otherwise.
312 Error and \-1 returns are the same as for
314 plus \[aq]?\[aq] for an
315 ambiguous match or an extraneous parameter.
319 If this is set, then option processing stops as soon as a nonoption
320 argument is encountered.
322 .B _<PID>_GNU_nonoption_argv_flags_
323 This variable was used by
325 2.0 to communicate to glibc which arguments are the results of
326 wildcard expansion and so should not be considered as options.
327 This behavior was removed in
329 2.01, but the support remains in glibc.
331 For an explanation of the terms used in this section, see
337 Interface Attribute Value
343 .BR getopt_long_only ()
347 MT-Unsafe race:getopt env
351 POSIX specifies that the
353 array argument should be
355 but these functions permute its elements
356 unless the environment variable
360 is used in the actual prototype to be compatible with other systems;
361 however, this page doesn't show the qualifier,
362 to avoid confusing readers.
370 .BR getopt_long_only ()
373 The use of \[aq]+\[aq] and \[aq]\-\[aq] in
379 POSIX.1-2001, and POSIX.2.
381 On some older implementations,
385 SUSv1 permitted the declaration to appear in either
389 POSIX.1-1996 marked the use of
391 for this purpose as LEGACY.
392 POSIX.1-2001 does not require the declaration to appear in
395 A program that scans multiple argument vectors,
396 or rescans the same vector more than once,
397 and wants to make use of GNU extensions such as \[aq]+\[aq]
398 and \[aq]\-\[aq] at the start of
400 or changes the value of
407 to 0, rather than the traditional value of 1.
408 (Resetting to 0 forces the invocation of an internal initialization
409 routine that rechecks
411 and checks for GNU extensions in
414 Command-line arguments are parsed in strict order
415 meaning that an option requiring an argument will consume the next argument,
416 regardless of whether that argument is the correctly specified option argument
417 or simply the next option
418 (in the scenario the user mis-specifies the command line).
421 is specified as "1n:"
422 and the user specifies the command line arguments incorrectly as
423 .IR "prog\ \-n\ \-1" ,
426 option will be given the
430 option will be considered to have not been specified.
433 The following trivial example program uses
435 to handle two program options:
437 with no associated value; and
439 which expects an associated value.
441 .\" SRC BEGIN (getopt.c)
448 main(int argc, char *argv[])
456 while ((opt = getopt(argc, argv, "nt:")) != \-1) {
462 nsecs = atoi(optarg);
465 default: /* \[aq]?\[aq] */
466 fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en",
472 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\en",
473 flags, tfnd, nsecs, optind);
475 if (optind >= argc) {
476 fprintf(stderr, "Expected argument after options\en");
480 printf("name argument = %s\en", argv[optind]);
482 /* Other code omitted */
489 The following example program illustrates the use of
491 with most of its features.
493 .\" SRC BEGIN (getopt_long.c)
496 #include <stdio.h> /* for printf */
497 #include <stdlib.h> /* for exit */
500 main(int argc, char *argv[])
503 int digit_optind = 0;
506 int this_option_optind = optind ? optind : 1;
507 int option_index = 0;
508 static struct option long_options[] = {
509 {"add", required_argument, 0, 0 },
510 {"append", no_argument, 0, 0 },
511 {"delete", required_argument, 0, 0 },
512 {"verbose", no_argument, 0, 0 },
513 {"create", required_argument, 0, \[aq]c\[aq]},
514 {"file", required_argument, 0, 0 },
518 c = getopt_long(argc, argv, "abc:d:012",
519 long_options, &option_index);
525 printf("option %s", long_options[option_index].name);
527 printf(" with arg %s", optarg);
534 if (digit_optind != 0 && digit_optind != this_option_optind)
535 printf("digits occur in two different argv\-elements.\en");
536 digit_optind = this_option_optind;
537 printf("option %c\en", c);
541 printf("option a\en");
545 printf("option b\en");
549 printf("option c with value \[aq]%s\[aq]\en", optarg);
553 printf("option d with value \[aq]%s\[aq]\en", optarg);
560 printf("?? getopt returned character code 0%o ??\en", c);
565 printf("non\-option ARGV\-elements: ");
566 while (optind < argc)
567 printf("%s ", argv[optind++]);