share/mk/: Fix includes
[man-pages.git] / man3 / getopt.3
blob02d0ea1418475e23a2a89d0110a0d96ac7558bda
1 '\" t
2 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
3 .\" and Copyright 2006-2008, Michael Kerrisk <mtk.manpages@gmail.com>
4 .\"
5 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\"
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.
22 .\"
23 .TH getopt 3 (date) "Linux man-pages (unreleased)"
24 .SH NAME
25 getopt, getopt_long, getopt_long_only,
26 optarg, optind, opterr, optopt \- Parse command-line options
27 .SH LIBRARY
28 Standard C library
29 .RI ( libc ", " \-lc )
30 .SH SYNOPSIS
31 .nf
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 );
48 .fi
50 .RS -4
51 Feature Test Macro Requirements for glibc (see
52 .BR feature_test_macros (7)):
53 .RE
55 .BR getopt ():
56 .nf
57     _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
58 .fi
60 .BR getopt_long (),
61 .BR getopt_long_only ():
62 .nf
63     _GNU_SOURCE
64 .fi
65 .SH DESCRIPTION
66 The
67 .BR getopt ()
68 function parses the command-line arguments.
69 Its arguments
70 .I argc
71 and
72 .I argv
73 are the argument count and array as passed to the
74 .IR main ()
75 function on program invocation.
76 An element of \fIargv\fP that starts with \[aq]\-\[aq]
77 (and is not exactly "\-" or "\-\-")
78 is an option element.
79 The characters of this element
80 (aside from the initial \[aq]\-\[aq]) are option characters.
82 .BR getopt ()
83 is called repeatedly, it returns successively each of the option characters
84 from each of the option elements.
86 The variable
87 .I optind
88 is the index of the next element to be processed in
89 .IR argv .
90 The system initializes this value to 1.
91 The caller can reset it to 1 to restart scanning of the same
92 .IR argv ,
93 or when scanning a new argument vector.
96 .BR getopt ()
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
100 .BR getopt ()
102 resume the scan with the following option character or
103 \fIargv\fP-element.
105 If there are no more option characters,
106 .BR getopt ()
107 returns \-1.
108 Then \fIoptind\fP is the index in \fIargv\fP of the first
109 \fIargv\fP-element that is not an option.
111 .I optstring
112 is a string containing the legitimate option characters.
113 A legitimate option character is any visible one byte
114 .BR ascii (7)
115 character (for which
116 .BR isgraph (3)
117 would return nonzero) that is not \[aq]\-\[aq], \[aq]:\[aq], or \[aq];\[aq].
118 If such a
119 character is followed by a colon, the option requires an argument, so
120 .BR getopt ()
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
123 .IR optarg .
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.
130 .I optstring
131 contains
132 .B W
133 followed by a semicolon, then
134 .B \-W foo
135 is treated as the long option
136 .BR \-\-foo .
137 (The
138 .B \-W
139 option is reserved by POSIX.2 for implementation extensions.)
140 This behavior is a GNU extension, not available with libraries before
141 glibc 2.
143 By default,
144 .BR getopt ()
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
150 .B POSIXLY_CORRECT
151 is set, then option processing stops as soon as a nonoption argument is
152 encountered.
153 If \[aq]+\[aq] is not the first character of
154 .IR optstring ,
155 it is treated as a normal option.
157 .B POSIXLY_CORRECT
158 behaviour is required in this case
159 .I optstring
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,
171 .BR getopt ()
172 can detect two kinds of errors:
173 (1) an option character that was not specified in
174 .I optstring
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:
178 .IP \[bu] 3
179 By default,
180 .BR getopt ()
181 prints an error message on standard error,
182 places the erroneous option character in
183 .IR optopt ,
184 and returns \[aq]?\[aq] as the function result.
185 .IP \[bu]
186 If the caller has set the global variable
187 .I opterr
188 to zero, then
189 .BR getopt ()
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].
193 (By default,
194 .I opterr
195 has a nonzero value.)
196 .IP \[bu]
197 If the first character
198 (following any optional \[aq]+\[aq] or \[aq]\-\[aq] described above)
199 of \fIoptstring\fP
200 is a colon (\[aq]:\[aq]), then
201 .BR getopt ()
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()
209 .BR getopt_long ()
210 function works like
211 .BR getopt ()
212 except that it also accepts long options, started with two dashes.
213 (If the program accepts only long options, then
214 .I optstring
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.
218 A long option
219 may take a parameter, of the form
220 .B \-\-arg=param
222 .BR "\-\-arg param" .
224 .I longopts
225 is a pointer to the first element of an array of
226 .I struct option
227 declared in
228 .I <getopt.h>
231 .in +4n
233 struct option {
234     const char *name;
235     int         has_arg;
236     int        *flag;
237     int         val;
242 The meanings of the different fields are:
244 .I name
245 is the name of the long option.
247 .I has_arg
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.
253 .I flag
254 specifies how results are returned for a long option.
255 If \fIflag\fP
256 is NULL, then
257 .BR getopt_long ()
258 returns \fIval\fP.
259 (For example, the calling program may set \fIval\fP to the equivalent short
260 option character.)
261 Otherwise,
262 .BR getopt_long ()
263 returns 0, and
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.
267 \fIval\fP
268 is the value to return, or to load into the variable pointed
269 to by \fIflag\fP.
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
275 .IR longopts .
277 .BR getopt_long_only ()
278 is like
279 .BR getopt_long (),
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.
285 .SH RETURN VALUE
286 If an option was successfully found, then
287 .BR getopt ()
288 returns the option character.
289 If all command-line options have been parsed, then
290 .BR getopt ()
291 returns \-1.
293 .BR getopt ()
294 encounters an option character that was not in
295 .IR optstring ,
296 then \[aq]?\[aq] is returned.
298 .BR getopt ()
299 encounters an option with a missing argument,
300 then the return value depends on the first character in
301 .IR optstring :
302 if it is \[aq]:\[aq], then \[aq]:\[aq] is returned;
303 otherwise \[aq]?\[aq] is returned.
305 .BR getopt_long ()
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
313 .BR getopt (),
314 plus \[aq]?\[aq] for an
315 ambiguous match or an extraneous parameter.
316 .SH ENVIRONMENT
318 .B POSIXLY_CORRECT
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
324 .BR bash (1)
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
328 .BR bash (1)
329 2.01, but the support remains in glibc.
330 .SH ATTRIBUTES
331 For an explanation of the terms used in this section, see
332 .BR attributes (7).
334 allbox;
335 lb lb lbx
336 l l l.
337 Interface       Attribute       Value
341 .BR getopt (),
342 .BR getopt_long (),
343 .BR getopt_long_only ()
344 T}      Thread safety   T{
347 MT-Unsafe race:getopt env
350 .SH VERSIONS
351 POSIX specifies that the
352 .I argv
353 array argument should be
354 .IR const ,
355 but these functions permute its elements
356 unless the environment variable
357 .B POSIXLY_CORRECT
358 is set.
359 .I const
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.
363 .SH STANDARDS
365 .BR getopt ()
366 POSIX.1-2008.
368 .BR getopt_long ()
370 .BR getopt_long_only ()
371 GNU.
373 The use of \[aq]+\[aq] and \[aq]\-\[aq] in
374 .I optstring
375 is a GNU extension.
376 .SH HISTORY
378 .BR getopt ()
379 POSIX.1-2001, and POSIX.2.
381 On some older implementations,
382 .BR getopt ()
383 was declared in
384 .IR <stdio.h> .
385 SUSv1 permitted the declaration to appear in either
386 .I <unistd.h>
388 .IR <stdio.h> .
389 POSIX.1-1996 marked the use of
390 .I <stdio.h>
391 for this purpose as LEGACY.
392 POSIX.1-2001 does not require the declaration to appear in
393 .IR <stdio.h> .
394 .SH NOTES
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
399 .IR optstring ,
400 or changes the value of
401 .B POSIXLY_CORRECT
402 between scans,
403 must reinitialize
404 .BR getopt ()
405 by resetting
406 .I optind
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
410 .B POSIXLY_CORRECT
411 and checks for GNU extensions in
412 .IR optstring .)
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).
419 For example, if
420 .I optstring
421 is specified as "1n:"
422 and the user specifies the command line arguments incorrectly as
423 .IR "prog\ \-n\ \-1" ,
425 .I \-n
426 option will be given the
427 .B optarg
428 value "\-1", and the
429 .I \-1
430 option will be considered to have not been specified.
431 .SH EXAMPLES
432 .SS getopt()
433 The following trivial example program uses
434 .BR getopt ()
435 to handle two program options:
436 .IR \-n ,
437 with no associated value; and
438 .IR "\-t val" ,
439 which expects an associated value.
441 .\" SRC BEGIN (getopt.c)
443 #include <stdio.h>
444 #include <stdlib.h>
445 #include <unistd.h>
448 main(int argc, char *argv[])
450     int flags, opt;
451     int nsecs, tfnd;
453     nsecs = 0;
454     tfnd = 0;
455     flags = 0;
456     while ((opt = getopt(argc, argv, "nt:")) != \-1) {
457         switch (opt) {
458         case \[aq]n\[aq]:
459             flags = 1;
460             break;
461         case \[aq]t\[aq]:
462             nsecs = atoi(optarg);
463             tfnd = 1;
464             break;
465         default: /* \[aq]?\[aq] */
466             fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en",
467                     argv[0]);
468             exit(EXIT_FAILURE);
469         }
470     }
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");
477         exit(EXIT_FAILURE);
478     }
480     printf("name argument = %s\en", argv[optind]);
482     /* Other code omitted */
484     exit(EXIT_SUCCESS);
487 .\" SRC END
488 .SS getopt_long()
489 The following example program illustrates the use of
490 .BR getopt_long ()
491 with most of its features.
493 .\" SRC BEGIN (getopt_long.c)
495 #include <getopt.h>
496 #include <stdio.h>     /* for printf */
497 #include <stdlib.h>    /* for exit */
500 main(int argc, char *argv[])
502     int c;
503     int digit_optind = 0;
505     while (1) {
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 },
515             {0,         0,                 0,  0 }
516         };
518         c = getopt_long(argc, argv, "abc:d:012",
519                         long_options, &option_index);
520         if (c == \-1)
521             break;
523         switch (c) {
524         case 0:
525             printf("option %s", long_options[option_index].name);
526             if (optarg)
527                 printf(" with arg %s", optarg);
528             printf("\en");
529             break;
531         case \[aq]0\[aq]:
532         case \[aq]1\[aq]:
533         case \[aq]2\[aq]:
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);
538             break;
540         case \[aq]a\[aq]:
541             printf("option a\en");
542             break;
544         case \[aq]b\[aq]:
545             printf("option b\en");
546             break;
548         case \[aq]c\[aq]:
549             printf("option c with value \[aq]%s\[aq]\en", optarg);
550             break;
552         case \[aq]d\[aq]:
553             printf("option d with value \[aq]%s\[aq]\en", optarg);
554             break;
556         case \[aq]?\[aq]:
557             break;
559         default:
560             printf("?? getopt returned character code 0%o ??\en", c);
561         }
562     }
564     if (optind < argc) {
565         printf("non\-option ARGV\-elements: ");
566         while (optind < argc)
567             printf("%s ", argv[optind++]);
568         printf("\en");
569     }
571     exit(EXIT_SUCCESS);
574 .\" SRC END
575 .SH SEE ALSO
576 .BR getopt (1),
577 .BR getsubopt (3)