1 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
2 .\" and Copyright 2006-2008, Michael Kerrisk <mtk.manpages@gmail.com>
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\" Modified Sat Jul 24 19:27:50 1993 by Rik Faith (faith@cs.unc.edu)
7 .\" Modified Mon Aug 30 22:02:34 1995 by Jim Van Zandt <jrv@vanzandt.mv.com>
8 .\" longindex is a pointer, has_arg can take 3 values, using consistent
9 .\" names for optstring and longindex, "\n" in formats fixed. Documenting
10 .\" opterr and getopt_long_only. Clarified explanations (borrowing heavily
11 .\" from the source code).
12 .\" Modified 8 May 1998 by Joseph S. Myers (jsm28@cam.ac.uk)
13 .\" Modified 990715, aeb: changed `EOF' into `-1' since that is what POSIX
14 .\" says; moreover, EOF is not defined in <unistd.h>.
15 .\" Modified 2002-02-16, joey: added information about nonexistent
16 .\" option character and colon as first option character
17 .\" Modified 2004-07-28, Michael Kerrisk <mtk.manpages@gmail.com>
18 .\" Added text to explain how to order both '[-+]' and ':' at
19 .\" the start of optstring
20 .\" Modified 2006-12-15, mtk, Added getopt() example program.
22 .TH GETOPT 3 2021-08-27 "GNU" "Linux Programmer's Manual"
24 getopt, getopt_long, getopt_long_only,
25 optarg, optind, opterr, optopt \- Parse command-line options
28 .RI ( libc ", " \-lc )
31 .B #include <unistd.h>
33 .BI "int getopt(int " argc ", char *const " argv [],
34 .BI " const char *" optstring );
36 .BI "extern char *" optarg ;
37 .BI "extern int " optind ", " opterr ", " optopt ;
39 .B #include <getopt.h>
41 .BI "int getopt_long(int " argc ", char *const " argv [],
42 .BI " const char *" optstring ,
43 .BI " const struct option *" longopts ", int *" longindex );
44 .BI "int getopt_long_only(int " argc ", char *const " argv [],
45 .BI " const char *" optstring ,
46 .BI " const struct option *" longopts ", int *" longindex );
50 Feature Test Macro Requirements for glibc (see
51 .BR feature_test_macros (7)):
56 _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
60 .BR getopt_long_only ():
67 function parses the command-line arguments.
72 are the argument count and array as passed to the
74 function on program invocation.
75 An element of \fIargv\fP that starts with \(aq\-\(aq
76 (and is not exactly "\-" or "\-\-")
78 The characters of this element
79 (aside from the initial \(aq\-\(aq) are option characters.
82 is called repeatedly, it returns successively each of the option characters
83 from each of the option elements.
87 is the index of the next element to be processed in
89 The system initializes this value to 1.
90 The caller can reset it to 1 to restart scanning of the same
92 or when scanning a new argument vector.
96 finds another option character, it returns that
97 character, updating the external variable \fIoptind\fP and a static
98 variable \fInextchar\fP so that the next call to
101 resume the scan with the following option character or
104 If there are no more option characters,
107 Then \fIoptind\fP is the index in \fIargv\fP of the first
108 \fIargv\fP-element that is not an option.
111 is a string containing the legitimate option characters.
112 A legitimate option character is any visible one byte
116 would return nonzero) that is not \(aq\-\(aq, \(aq:\(aq, or \(aq;\(aq.
118 character is followed by a colon, the option requires an argument, so
120 places a pointer to the following text in the same
121 \fIargv\fP-element, or the text of the following \fIargv\fP-element, in
123 Two colons mean an option takes
124 an optional arg; if there is text in the current \fIargv\fP-element
125 (i.e., in the same word as the option name itself, for example, "\-oarg"),
126 then it is returned in \fIoptarg\fP, otherwise \fIoptarg\fP is set to zero.
127 This is a GNU extension.
132 followed by a semicolon, then
134 is treated as the long option
138 option is reserved by POSIX.2 for implementation extensions.)
139 This behavior is a GNU extension, not available with libraries before
144 permutes the contents of \fIargv\fP as it
145 scans, so that eventually all the nonoptions are at the end.
146 Two other scanning modes are also implemented.
147 If the first character of
148 \fIoptstring\fP is \(aq+\(aq or the environment variable
150 is set, then option processing stops as soon as a nonoption argument is
152 If \(aq+\(aq is not the first character of
154 it is treated as a normal option.
157 behaviour is required in this case
159 will contain two \(aq+\(aq symbols.
160 If the first character of \fIoptstring\fP is \(aq\-\(aq, then
161 each nonoption \fIargv\fP-element is handled as if it were the argument of
162 an option with character code 1.
163 (This is used by programs that were
164 written to expect options and other \fIargv\fP-elements in any order
165 and that care about the ordering of the two.)
166 The special argument "\-\-" forces an end of option-scanning regardless
167 of the scanning mode.
169 While processing the option list,
171 can detect two kinds of errors:
172 (1) an option character that was not specified in
174 and (2) a missing option argument
175 (i.e., an option at the end of the command line without an expected argument).
176 Such errors are handled and reported as follows:
180 prints an error message on standard error,
181 places the erroneous option character in
183 and returns \(aq?\(aq as the function result.
185 If the caller has set the global variable
189 does not print an error message.
190 The caller can determine that there was an error by testing whether
191 the function return value is \(aq?\(aq.
194 has a nonzero value.)
196 If the first character
197 (following any optional \(aq+\(aq or \(aq\-\(aq described above)
199 is a colon (\(aq:\(aq), then
201 likewise does not print an error message.
202 In addition, it returns \(aq:\(aq instead of \(aq?\(aq to
203 indicate a missing option argument.
204 This allows the caller to distinguish the two different types of errors.
206 .SS getopt_long() and getopt_long_only()
211 except that it also accepts long options, started with two dashes.
212 (If the program accepts only long options, then
214 should be specified as an empty string (""), not NULL.)
215 Long option names may be abbreviated if the abbreviation is
216 unique or is an exact match for some defined option.
218 may take a parameter, of the form
221 .BR "\-\-arg param" .
224 is a pointer to the first element of an array of
241 The meanings of the different fields are:
244 is the name of the long option.
248 \fBno_argument\fP (or 0) if the option does not take an argument;
249 \fBrequired_argument\fP (or 1) if the option requires an argument; or
250 \fBoptional_argument\fP (or 2) if the option takes an optional argument.
253 specifies how results are returned for a long option.
258 (For example, the calling program may set \fIval\fP to the equivalent short
263 \fIflag\fP points to a variable which is set to \fIval\fP if the
264 option is found, but left unchanged if the option is not found.
267 is the value to return, or to load into the variable pointed
270 The last element of the array has to be filled with zeros.
272 If \fIlongindex\fP is not NULL, it
273 points to a variable which is set to the index of the long option relative to
276 .BR getopt_long_only ()
279 but \(aq\-\(aq as well
280 as "\-\-" can indicate a long option.
281 If an option that starts with \(aq\-\(aq
282 (not "\-\-") doesn't match a long option, but does match a short option,
283 it is parsed as a short option instead.
285 If an option was successfully found, then
287 returns the option character.
288 If all command-line options have been parsed, then
293 encounters an option character that was not in
295 then \(aq?\(aq is returned.
298 encounters an option with a missing argument,
299 then the return value depends on the first character in
301 if it is \(aq:\(aq, then \(aq:\(aq is returned; otherwise \(aq?\(aq is returned.
305 .BR getopt_long_only ()
306 also return the option
307 character when a short option is recognized.
308 For a long option, they
309 return \fIval\fP if \fIflag\fP is NULL, and 0 otherwise.
310 Error and \-1 returns are the same as for
312 plus \(aq?\(aq for an
313 ambiguous match or an extraneous parameter.
317 If this is set, then option processing stops as soon as a nonoption
318 argument is encountered.
320 .B _<PID>_GNU_nonoption_argv_flags_
321 This variable was used by
323 2.0 to communicate to glibc which arguments are the results of
324 wildcard expansion and so should not be considered as options.
325 This behavior was removed in
327 version 2.01, but the support remains in glibc.
329 For an explanation of the terms used in this section, see
337 Interface Attribute Value
341 .BR getopt_long_only ()
343 MT-Unsafe race:getopt env
352 POSIX.1-2001, POSIX.1-2008, and POSIX.2,
353 provided the environment variable
356 Otherwise, the elements of \fIargv\fP aren't really
358 because these functions permute them.
361 is used in the prototype to be compatible with other systems.
363 The use of \(aq+\(aq and \(aq\-\(aq in
367 On some older implementations,
371 SUSv1 permitted the declaration to appear in either
375 POSIX.1-1996 marked the use of
377 for this purpose as LEGACY.
378 POSIX.1-2001 does not require the declaration to appear in
381 .BR getopt_long "() and " getopt_long_only ():
382 These functions are GNU extensions.
384 A program that scans multiple argument vectors,
385 or rescans the same vector more than once,
386 and wants to make use of GNU extensions such as \(aq+\(aq
387 and \(aq\-\(aq at the start of
389 or changes the value of
396 to 0, rather than the traditional value of 1.
397 (Resetting to 0 forces the invocation of an internal initialization
398 routine that rechecks
400 and checks for GNU extensions in
403 Command-line arguments are parsed in strict order
404 meaning that an option requiring an argument will consume the next argument,
405 regardless of whether that argument is the correctly specified option argument
406 or simply the next option
407 (in the scenario the user mis-specifies the command line).
410 is specified as "1n:"
411 and the user specifies the command line arguments incorrectly as
412 .IR "prog\ \-n\ \-1" ,
415 option will be given the
419 option will be considered to have not been specified.
422 The following trivial example program uses
424 to handle two program options:
426 with no associated value; and
428 which expects an associated value.
436 main(int argc, char *argv[])
444 while ((opt = getopt(argc, argv, "nt:")) != \-1) {
450 nsecs = atoi(optarg);
453 default: /* \(aq?\(aq */
454 fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en",
460 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\en",
461 flags, tfnd, nsecs, optind);
463 if (optind >= argc) {
464 fprintf(stderr, "Expected argument after options\en");
468 printf("name argument = %s\en", argv[optind]);
470 /* Other code omitted */
476 The following example program illustrates the use of
478 with most of its features.
481 #include <stdio.h> /* for printf */
482 #include <stdlib.h> /* for exit */
486 main(int argc, char *argv[])
489 int digit_optind = 0;
492 int this_option_optind = optind ? optind : 1;
493 int option_index = 0;
494 static struct option long_options[] = {
495 {"add", required_argument, 0, 0 },
496 {"append", no_argument, 0, 0 },
497 {"delete", required_argument, 0, 0 },
498 {"verbose", no_argument, 0, 0 },
499 {"create", required_argument, 0, \(aqc\(aq},
500 {"file", required_argument, 0, 0 },
504 c = getopt_long(argc, argv, "abc:d:012",
505 long_options, &option_index);
511 printf("option %s", long_options[option_index].name);
513 printf(" with arg %s", optarg);
520 if (digit_optind != 0 && digit_optind != this_option_optind)
521 printf("digits occur in two different argv\-elements.\en");
522 digit_optind = this_option_optind;
523 printf("option %c\en", c);
527 printf("option a\en");
531 printf("option b\en");
535 printf("option c with value \(aq%s\(aq\en", optarg);
539 printf("option d with value \(aq%s\(aq\en", optarg);
546 printf("?? getopt returned character code 0%o ??\en", c);
551 printf("non\-option ARGV\-elements: ");
552 while (optind < argc)
553 printf("%s ", argv[optind++]);