getopt.3: Minor tweak to James's patch
[man-pages.git] / man3 / getopt.3
blobf5970075d22011a83078fc13e8a3a21dc4d86075
1 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
2 .\" and Copyright 2006-2008, Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein.  The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .\" Modified Sat Jul 24 19:27:50 1993 by Rik Faith (faith@cs.unc.edu)
27 .\" Modified Mon Aug 30 22:02:34 1995 by Jim Van Zandt <jrv@vanzandt.mv.com>
28 .\"  longindex is a pointer, has_arg can take 3 values, using consistent
29 .\"  names for optstring and longindex, "\n" in formats fixed.  Documenting
30 .\"  opterr and getopt_long_only.  Clarified explanations (borrowing heavily
31 .\"  from the source code).
32 .\" Modified 8 May 1998 by Joseph S. Myers (jsm28@cam.ac.uk)
33 .\" Modified 990715, aeb: changed `EOF' into `-1' since that is what POSIX
34 .\"  says; moreover, EOF is not defined in <unistd.h>.
35 .\" Modified 2002-02-16, joey: added information about nonexistent
36 .\"  option character and colon as first option character
37 .\" Modified 2004-07-28, Michael Kerrisk <mtk.manpages@gmail.com>
38 .\"     Added text to explain how to order both '[-+]' and ':' at
39 .\"             the start of optstring
40 .\" Modified 2006-12-15, mtk, Added getopt() example program.
41 .\"
42 .TH GETOPT 3  2021-03-22 "GNU" "Linux Programmer's Manual"
43 .SH NAME
44 getopt, getopt_long, getopt_long_only,
45 optarg, optind, opterr, optopt \- Parse command-line options
46 .SH SYNOPSIS
47 .nf
48 .B #include <unistd.h>
49 .PP
50 .BI "int getopt(int " argc ", char *const " argv [],
51 .BI "           const char *" optstring );
52 .PP
53 .BI "extern char *" optarg ;
54 .BI "extern int " optind ", " opterr ", " optopt ;
55 .PP
56 .B #include <getopt.h>
57 .PP
58 .BI "int getopt_long(int " argc ", char *const " argv [],
59 .BI "           const char *" optstring ,
60 .BI "           const struct option *" longopts ", int *" longindex );
61 .BI "int getopt_long_only(int " argc ", char *const " argv [],
62 .BI "           const char *" optstring ,
63 .BI "           const struct option *" longopts ", int *" longindex );
64 .fi
65 .PP
66 .RS -4
67 Feature Test Macro Requirements for glibc (see
68 .BR feature_test_macros (7)):
69 .RE
70 .PP
71 .BR getopt ():
72 .nf
73     _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
74 .fi
75 .PP
76 .BR getopt_long (),
77 .BR getopt_long_only ():
78 .nf
79     _GNU_SOURCE
80 .fi
81 .SH DESCRIPTION
82 The
83 .BR getopt ()
84 function parses the command-line arguments.
85 Its arguments
86 .I argc
87 and
88 .I argv
89 are the argument count and array as passed to the
90 .IR main ()
91 function on program invocation.
92 An element of \fIargv\fP that starts with \(aq\-\(aq
93 (and is not exactly "\-" or "\-\-")
94 is an option element.
95 The characters of this element
96 (aside from the initial \(aq\-\(aq) are option characters.
98 .BR getopt ()
99 is called repeatedly, it returns successively each of the option characters
100 from each of the option elements.
102 The variable
103 .I optind
104 is the index of the next element to be processed in
105 .IR argv .
106 The system initializes this value to 1.
107 The caller can reset it to 1 to restart scanning of the same
108 .IR argv ,
109 or when scanning a new argument vector.
112 .BR getopt ()
113 finds another option character, it returns that
114 character, updating the external variable \fIoptind\fP and a static
115 variable \fInextchar\fP so that the next call to
116 .BR getopt ()
118 resume the scan with the following option character or
119 \fIargv\fP-element.
121 If there are no more option characters,
122 .BR getopt ()
123 returns \-1.
124 Then \fIoptind\fP is the index in \fIargv\fP of the first
125 \fIargv\fP-element that is not an option.
127 .I optstring
128 is a string containing the legitimate option characters.
129 A legitimate option character is any visible one byte
130 .BR ascii (7)
131 character (for which
132 .BR isgraph (3)
133 would return nonzero) that is not \(aq\-\(aq, \(aq:\(aq, or \(aq;\(aq.
134 If such a
135 character is followed by a colon, the option requires an argument, so
136 .BR getopt ()
137 places a pointer to the following text in the same
138 \fIargv\fP-element, or the text of the following \fIargv\fP-element, in
139 .IR optarg .
140 Two colons mean an option takes
141 an optional arg; if there is text in the current \fIargv\fP-element
142 (i.e., in the same word as the option name itself, for example, "\-oarg"),
143 then it is returned in \fIoptarg\fP, otherwise \fIoptarg\fP is set to zero.
144 This is a GNU extension.
146 .I optstring
147 contains
148 .B W
149 followed by a semicolon, then
150 .B \-W foo
151 is treated as the long option
152 .BR \-\-foo .
153 (The
154 .B \-W
155 option is reserved by POSIX.2 for implementation extensions.)
156 This behavior is a GNU extension, not available with libraries before
157 glibc 2.
159 By default,
160 .BR getopt ()
161 permutes the contents of \fIargv\fP as it
162 scans, so that eventually all the nonoptions are at the end.
163 Two other scanning modes are also implemented.
164 If the first character of
165 \fIoptstring\fP is \(aq+\(aq or the environment variable
166 .B POSIXLY_CORRECT
167 is set, then option processing stops as soon as a nonoption argument is
168 encountered.
169 If \(aq+\(aq is not the first character of
170 .IR optstring ,
171 it is treated as a normal option.
173 .B POSIXLY_CORRECT
174 behaviour is required in this case
175 .I optstring
176 will contain two \(aq+\(aq symbols.
177 If the first character of \fIoptstring\fP is \(aq\-\(aq, then
178 each nonoption \fIargv\fP-element is handled as if it were the argument of
179 an option with character code 1.  (This is used by programs that were
180 written to expect options and other \fIargv\fP-elements in any order
181 and that care about the ordering of the two.)
182 The special argument "\-\-" forces an end of option-scanning regardless
183 of the scanning mode.
185 While processing the option list,
186 .BR getopt ()
187 can detect two kinds of errors:
188 (1) an option character that was not specified in
189 .IR optstring
190 and (2) a missing option argument
191 (i.e., an option at the end of the command line without an expected argument).
192 Such errors are handled and reported as follows:
193 .IP * 3
194 By default,
195 .BR getopt ()
196 prints an error message on standard error,
197 places the erroneous option character in
198 .IR optopt ,
199 and returns \(aq?\(aq as the function result.
200 .IP *
201 If the caller has set the global variable
202 .IR opterr
203 to zero, then
204 .BR getopt ()
205 does not print an error message.
206 The caller can determine that there was an error by testing whether
207 the function return value is \(aq?\(aq.
208 (By default,
209 .IR opterr
210 has a nonzero value.)
211 .IP *
212 If the first character
213 (following any optional \(aq+\(aq or \(aq\-\(aq described above)
214 of \fIoptstring\fP
215 is a colon (\(aq:\(aq), then
216 .BR getopt ()
217 likewise does not print an error message.
218 In addition, it returns \(aq:\(aq instead of \(aq?\(aq to
219 indicate a missing option argument.
220 This allows the caller to distinguish the two different types of errors.
222 .SS getopt_long() and getopt_long_only()
224 .BR getopt_long ()
225 function works like
226 .BR getopt ()
227 except that it also accepts long options, started with two dashes.
228 (If the program accepts only long options, then
229 .I optstring
230 should be specified as an empty string (""), not NULL.)
231 Long option names may be abbreviated if the abbreviation is
232 unique or is an exact match for some defined option.
233 A long option
234 may take a parameter, of the form
235 .B \-\-arg=param
237 .BR "\-\-arg param" .
239 .I longopts
240 is a pointer to the first element of an array of
241 .I struct option
242 declared in
243 .I <getopt.h>
246 .in +4n
248 struct option {
249     const char *name;
250     int         has_arg;
251     int        *flag;
252     int         val;
257 The meanings of the different fields are:
259 .I name
260 is the name of the long option.
262 .I has_arg
264 \fBno_argument\fP (or 0) if the option does not take an argument;
265 \fBrequired_argument\fP (or 1) if the option requires an argument; or
266 \fBoptional_argument\fP (or 2) if the option takes an optional argument.
268 .I flag
269 specifies how results are returned for a long option.
270 If \fIflag\fP
271 is NULL, then
272 .BR getopt_long ()
273 returns \fIval\fP.
274 (For example, the calling program may set \fIval\fP to the equivalent short
275 option character.)
276 Otherwise,
277 .BR getopt_long ()
278 returns 0, and
279 \fIflag\fP points to a variable which is set to \fIval\fP if the
280 option is found, but left unchanged if the option is not found.
282 \fIval\fP
283 is the value to return, or to load into the variable pointed
284 to by \fIflag\fP.
286 The last element of the array has to be filled with zeros.
288 If \fIlongindex\fP is not NULL, it
289 points to a variable which is set to the index of the long option relative to
290 .IR longopts .
292 .BR getopt_long_only ()
293 is like
294 .BR getopt_long (),
295 but \(aq\-\(aq as well
296 as "\-\-" can indicate a long option.
297 If an option that starts with \(aq\-\(aq
298 (not "\-\-") doesn't match a long option, but does match a short option,
299 it is parsed as a short option instead.
300 .SH RETURN VALUE
301 If an option was successfully found, then
302 .BR getopt ()
303 returns the option character.
304 If all command-line options have been parsed, then
305 .BR getopt ()
306 returns \-1.
308 .BR getopt ()
309 encounters an option character that was not in
310 .IR optstring ,
311 then \(aq?\(aq is returned.
313 .BR getopt ()
314 encounters an option with a missing argument,
315 then the return value depends on the first character in
316 .IR optstring :
317 if it is \(aq:\(aq, then \(aq:\(aq is returned; otherwise \(aq?\(aq is returned.
319 .BR getopt_long ()
321 .BR getopt_long_only ()
322 also return the option
323 character when a short option is recognized.
324 For a long option, they
325 return \fIval\fP if \fIflag\fP is NULL, and 0 otherwise.
326 Error and \-1 returns are the same as for
327 .BR getopt (),
328 plus \(aq?\(aq for an
329 ambiguous match or an extraneous parameter.
330 .SH ENVIRONMENT
332 .B POSIXLY_CORRECT
333 If this is set, then option processing stops as soon as a nonoption
334 argument is encountered.
336 .B _<PID>_GNU_nonoption_argv_flags_
337 This variable was used by
338 .BR bash (1)
339 2.0 to communicate to glibc which arguments are the results of
340 wildcard expansion and so should not be considered as options.
341 This behavior was removed in
342 .BR bash (1)
343 version 2.01, but the support remains in glibc.
344 .SH ATTRIBUTES
345 For an explanation of the terms used in this section, see
346 .BR attributes (7).
347 .ad l
350 allbox;
351 lb lb lbx
352 l l l.
353 Interface       Attribute       Value
355 .BR getopt (),
356 .BR getopt_long (),
357 .BR getopt_long_only ()
358 T}      Thread safety   T{
359 MT-Unsafe race:getopt env
364 .sp 1
365 .SH CONFORMING TO
367 .BR getopt ():
368 POSIX.1-2001, POSIX.1-2008, and POSIX.2,
369 provided the environment variable
370 .B POSIXLY_CORRECT
371 is set.
372 Otherwise, the elements of \fIargv\fP aren't really
373 .IR const ,
374 because these functions permute them.
375 Nevertheless,
376 .I const
377 is used in the prototype to be compatible with other systems.
379 The use of \(aq+\(aq and \(aq\-\(aq in
380 .I optstring
381 is a GNU extension.
383 On some older implementations,
384 .BR getopt ()
385 was declared in
386 .IR <stdio.h> .
387 SUSv1 permitted the declaration to appear in either
388 .I <unistd.h>
390 .IR <stdio.h> .
391 POSIX.1-1996 marked the use of
392 .I <stdio.h>
393 for this purpose as LEGACY.
394 POSIX.1-2001 does not require the declaration to appear in
395 .IR <stdio.h> .
397 .BR getopt_long "() and " getopt_long_only ():
398 These functions are GNU extensions.
399 .SH NOTES
400 A program that scans multiple argument vectors,
401 or rescans the same vector more than once,
402 and wants to make use of GNU extensions such as \(aq+\(aq
403 and \(aq\-\(aq at the start of
404 .IR optstring ,
405 or changes the value of
406 .B POSIXLY_CORRECT
407 between scans,
408 must reinitialize
409 .BR getopt ()
410 by resetting
411 .I optind
412 to 0, rather than the traditional value of 1.
413 (Resetting to 0 forces the invocation of an internal initialization
414 routine that rechecks
415 .B POSIXLY_CORRECT
416 and checks for GNU extensions in
417 .IR optstring .)
419 Command-line arguments are parsed in strict order
420 meaning that an option requiring an argument will consume the next argument,
421 regardless of whether that argument is the correctly specified option argument
422 or simply the next option
423 (in the scenario the user mis-specifies the command line).
424 For example, if
425 .I optstring
426 is specified as "1n:"
427 and the user specifies the command line arguments incorrectly as
428 .IR "prog\ \-n\ \-1" ,
430 .I \-n
431 option will be given the
432 .B optarg
433 value "\-1", and the
434 .I \-1
435 option will be considered to have not been specified.
436 .SH EXAMPLES
437 .SS getopt()
438 The following trivial example program uses
439 .BR getopt ()
440 to handle two program options:
441 .IR \-n ,
442 with no associated value; and
443 .IR "\-t val" ,
444 which expects an associated value.
447 #include <unistd.h>
448 #include <stdlib.h>
449 #include <stdio.h>
452 main(int argc, char *argv[])
454     int flags, opt;
455     int nsecs, tfnd;
457     nsecs = 0;
458     tfnd = 0;
459     flags = 0;
460     while ((opt = getopt(argc, argv, "nt:")) != \-1) {
461         switch (opt) {
462         case \(aqn\(aq:
463             flags = 1;
464             break;
465         case \(aqt\(aq:
466             nsecs = atoi(optarg);
467             tfnd = 1;
468             break;
469         default: /* \(aq?\(aq */
470             fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en",
471                     argv[0]);
472             exit(EXIT_FAILURE);
473         }
474     }
476     printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\en",
477             flags, tfnd, nsecs, optind);
479     if (optind >= argc) {
480         fprintf(stderr, "Expected argument after options\en");
481         exit(EXIT_FAILURE);
482     }
484     printf("name argument = %s\en", argv[optind]);
486     /* Other code omitted */
488     exit(EXIT_SUCCESS);
491 .SS getopt_long()
492 The following example program illustrates the use of
493 .BR getopt_long ()
494 with most of its features.
497 #include <stdio.h>     /* for printf */
498 #include <stdlib.h>    /* for exit */
499 #include <getopt.h>
502 main(int argc, char *argv[])
504     int c;
505     int digit_optind = 0;
507     while (1) {
508         int this_option_optind = optind ? optind : 1;
509         int option_index = 0;
510         static struct option long_options[] = {
511             {"add",     required_argument, 0,  0 },
512             {"append",  no_argument,       0,  0 },
513             {"delete",  required_argument, 0,  0 },
514             {"verbose", no_argument,       0,  0 },
515             {"create",  required_argument, 0, \(aqc\(aq},
516             {"file",    required_argument, 0,  0 },
517             {0,         0,                 0,  0 }
518         };
520         c = getopt_long(argc, argv, "abc:d:012",
521                  long_options, &option_index);
522         if (c == \-1)
523             break;
525         switch (c) {
526         case 0:
527             printf("option %s", long_options[option_index].name);
528             if (optarg)
529                 printf(" with arg %s", optarg);
530             printf("\en");
531             break;
533         case \(aq0\(aq:
534         case \(aq1\(aq:
535         case \(aq2\(aq:
536             if (digit_optind != 0 && digit_optind != this_option_optind)
537               printf("digits occur in two different argv\-elements.\en");
538             digit_optind = this_option_optind;
539             printf("option %c\en", c);
540             break;
542         case \(aqa\(aq:
543             printf("option a\en");
544             break;
546         case \(aqb\(aq:
547             printf("option b\en");
548             break;
550         case \(aqc\(aq:
551             printf("option c with value \(aq%s\(aq\en", optarg);
552             break;
554         case \(aqd\(aq:
555             printf("option d with value \(aq%s\(aq\en", optarg);
556             break;
558         case \(aq?\(aq:
559             break;
561         default:
562             printf("?? getopt returned character code 0%o ??\en", c);
563         }
564     }
566     if (optind < argc) {
567         printf("non\-option ARGV\-elements: ");
568         while (optind < argc)
569             printf("%s ", argv[optind++]);
570         printf("\en");
571     }
573     exit(EXIT_SUCCESS);
576 .SH SEE ALSO
577 .BR getopt (1),
578 .BR getsubopt (3)