]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man3/getopt.3
eae52c57170b4db03291fae26c5d009a1f270304
[thirdparty/man-pages.git] / man3 / getopt.3
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 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
5 .\"
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.
21 .\"
22 .TH GETOPT 3 2021-08-27 "GNU" "Linux Programmer's Manual"
23 .SH NAME
24 getopt, getopt_long, getopt_long_only,
25 optarg, optind, opterr, optopt \- Parse command-line options
26 .SH LIBRARY
27 Standard C library
28 .RI ( libc ", " \-lc )
29 .SH SYNOPSIS
30 .nf
31 .B #include <unistd.h>
32 .PP
33 .BI "int getopt(int " argc ", char *const " argv [],
34 .BI " const char *" optstring );
35 .PP
36 .BI "extern char *" optarg ;
37 .BI "extern int " optind ", " opterr ", " optopt ;
38 .PP
39 .B #include <getopt.h>
40 .PP
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 );
47 .fi
48 .PP
49 .RS -4
50 Feature Test Macro Requirements for glibc (see
51 .BR feature_test_macros (7)):
52 .RE
53 .PP
54 .BR getopt ():
55 .nf
56 _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
57 .fi
58 .PP
59 .BR getopt_long (),
60 .BR getopt_long_only ():
61 .nf
62 _GNU_SOURCE
63 .fi
64 .SH DESCRIPTION
65 The
66 .BR getopt ()
67 function parses the command-line arguments.
68 Its arguments
69 .I argc
70 and
71 .I argv
72 are the argument count and array as passed to the
73 .IR main ()
74 function on program invocation.
75 An element of \fIargv\fP that starts with \(aq\-\(aq
76 (and is not exactly "\-" or "\-\-")
77 is an option element.
78 The characters of this element
79 (aside from the initial \(aq\-\(aq) are option characters.
80 If
81 .BR getopt ()
82 is called repeatedly, it returns successively each of the option characters
83 from each of the option elements.
84 .PP
85 The variable
86 .I optind
87 is the index of the next element to be processed in
88 .IR argv .
89 The system initializes this value to 1.
90 The caller can reset it to 1 to restart scanning of the same
91 .IR argv ,
92 or when scanning a new argument vector.
93 .PP
94 If
95 .BR getopt ()
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
99 .BR getopt ()
100 can
101 resume the scan with the following option character or
102 \fIargv\fP-element.
103 .PP
104 If there are no more option characters,
105 .BR getopt ()
106 returns \-1.
107 Then \fIoptind\fP is the index in \fIargv\fP of the first
108 \fIargv\fP-element that is not an option.
109 .PP
110 .I optstring
111 is a string containing the legitimate option characters.
112 A legitimate option character is any visible one byte
113 .BR ascii (7)
114 character (for which
115 .BR isgraph (3)
116 would return nonzero) that is not \(aq\-\(aq, \(aq:\(aq, or \(aq;\(aq.
117 If such a
118 character is followed by a colon, the option requires an argument, so
119 .BR getopt ()
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
122 .IR optarg .
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.
128 If
129 .I optstring
130 contains
131 .B W
132 followed by a semicolon, then
133 .B \-W foo
134 is treated as the long option
135 .BR \-\-foo .
136 (The
137 .B \-W
138 option is reserved by POSIX.2 for implementation extensions.)
139 This behavior is a GNU extension, not available with libraries before
140 glibc 2.
141 .PP
142 By default,
143 .BR getopt ()
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
149 .B POSIXLY_CORRECT
150 is set, then option processing stops as soon as a nonoption argument is
151 encountered.
152 If \(aq+\(aq is not the first character of
153 .IR optstring ,
154 it is treated as a normal option.
155 If
156 .B POSIXLY_CORRECT
157 behaviour is required in this case
158 .I optstring
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.
168 .PP
169 While processing the option list,
170 .BR getopt ()
171 can detect two kinds of errors:
172 (1) an option character that was not specified in
173 .IR optstring
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:
177 .IP * 3
178 By default,
179 .BR getopt ()
180 prints an error message on standard error,
181 places the erroneous option character in
182 .IR optopt ,
183 and returns \(aq?\(aq as the function result.
184 .IP *
185 If the caller has set the global variable
186 .IR opterr
187 to zero, then
188 .BR getopt ()
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.
192 (By default,
193 .IR opterr
194 has a nonzero value.)
195 .IP *
196 If the first character
197 (following any optional \(aq+\(aq or \(aq\-\(aq described above)
198 of \fIoptstring\fP
199 is a colon (\(aq:\(aq), then
200 .BR getopt ()
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.
205 .\"
206 .SS getopt_long() and getopt_long_only()
207 The
208 .BR getopt_long ()
209 function works like
210 .BR getopt ()
211 except that it also accepts long options, started with two dashes.
212 (If the program accepts only long options, then
213 .I optstring
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.
217 A long option
218 may take a parameter, of the form
219 .B \-\-arg=param
220 or
221 .BR "\-\-arg param" .
222 .PP
223 .I longopts
224 is a pointer to the first element of an array of
225 .I struct option
226 declared in
227 .I <getopt.h>
228 as
229 .PP
230 .in +4n
231 .EX
232 struct option {
233 const char *name;
234 int has_arg;
235 int *flag;
236 int val;
237 };
238 .EE
239 .in
240 .PP
241 The meanings of the different fields are:
242 .TP
243 .I name
244 is the name of the long option.
245 .TP
246 .I has_arg
247 is:
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.
251 .TP
252 .I flag
253 specifies how results are returned for a long option.
254 If \fIflag\fP
255 is NULL, then
256 .BR getopt_long ()
257 returns \fIval\fP.
258 (For example, the calling program may set \fIval\fP to the equivalent short
259 option character.)
260 Otherwise,
261 .BR getopt_long ()
262 returns 0, and
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.
265 .TP
266 \fIval\fP
267 is the value to return, or to load into the variable pointed
268 to by \fIflag\fP.
269 .PP
270 The last element of the array has to be filled with zeros.
271 .PP
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
274 .IR longopts .
275 .PP
276 .BR getopt_long_only ()
277 is like
278 .BR getopt_long (),
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.
284 .SH RETURN VALUE
285 If an option was successfully found, then
286 .BR getopt ()
287 returns the option character.
288 If all command-line options have been parsed, then
289 .BR getopt ()
290 returns \-1.
291 If
292 .BR getopt ()
293 encounters an option character that was not in
294 .IR optstring ,
295 then \(aq?\(aq is returned.
296 If
297 .BR getopt ()
298 encounters an option with a missing argument,
299 then the return value depends on the first character in
300 .IR optstring :
301 if it is \(aq:\(aq, then \(aq:\(aq is returned; otherwise \(aq?\(aq is returned.
302 .PP
303 .BR getopt_long ()
304 and
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
311 .BR getopt (),
312 plus \(aq?\(aq for an
313 ambiguous match or an extraneous parameter.
314 .SH ENVIRONMENT
315 .TP
316 .B POSIXLY_CORRECT
317 If this is set, then option processing stops as soon as a nonoption
318 argument is encountered.
319 .TP
320 .B _<PID>_GNU_nonoption_argv_flags_
321 This variable was used by
322 .BR bash (1)
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
326 .BR bash (1)
327 version 2.01, but the support remains in glibc.
328 .SH ATTRIBUTES
329 For an explanation of the terms used in this section, see
330 .BR attributes (7).
331 .ad l
332 .nh
333 .TS
334 allbox;
335 lb lb lbx
336 l l l.
337 Interface Attribute Value
338 T{
339 .BR getopt (),
340 .BR getopt_long (),
341 .BR getopt_long_only ()
342 T} Thread safety T{
343 MT-Unsafe race:getopt env
344 T}
345 .TE
346 .hy
347 .ad
348 .sp 1
349 .SH CONFORMING TO
350 .TP
351 .BR getopt ():
352 POSIX.1-2001, POSIX.1-2008, and POSIX.2,
353 provided the environment variable
354 .B POSIXLY_CORRECT
355 is set.
356 Otherwise, the elements of \fIargv\fP aren't really
357 .IR const ,
358 because these functions permute them.
359 Nevertheless,
360 .I const
361 is used in the prototype to be compatible with other systems.
362 .IP
363 The use of \(aq+\(aq and \(aq\-\(aq in
364 .I optstring
365 is a GNU extension.
366 .IP
367 On some older implementations,
368 .BR getopt ()
369 was declared in
370 .IR <stdio.h> .
371 SUSv1 permitted the declaration to appear in either
372 .I <unistd.h>
373 or
374 .IR <stdio.h> .
375 POSIX.1-1996 marked the use of
376 .I <stdio.h>
377 for this purpose as LEGACY.
378 POSIX.1-2001 does not require the declaration to appear in
379 .IR <stdio.h> .
380 .TP
381 .BR getopt_long "() and " getopt_long_only ():
382 These functions are GNU extensions.
383 .SH NOTES
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
388 .IR optstring ,
389 or changes the value of
390 .B POSIXLY_CORRECT
391 between scans,
392 must reinitialize
393 .BR getopt ()
394 by resetting
395 .I optind
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
399 .B POSIXLY_CORRECT
400 and checks for GNU extensions in
401 .IR optstring .)
402 .PP
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).
408 For example, if
409 .I optstring
410 is specified as "1n:"
411 and the user specifies the command line arguments incorrectly as
412 .IR "prog\ \-n\ \-1" ,
413 the
414 .I \-n
415 option will be given the
416 .B optarg
417 value "\-1", and the
418 .I \-1
419 option will be considered to have not been specified.
420 .SH EXAMPLES
421 .SS getopt()
422 The following trivial example program uses
423 .BR getopt ()
424 to handle two program options:
425 .IR \-n ,
426 with no associated value; and
427 .IR "\-t val" ,
428 which expects an associated value.
429 .PP
430 .EX
431 #include <unistd.h>
432 #include <stdlib.h>
433 #include <stdio.h>
434
435 int
436 main(int argc, char *argv[])
437 {
438 int flags, opt;
439 int nsecs, tfnd;
440
441 nsecs = 0;
442 tfnd = 0;
443 flags = 0;
444 while ((opt = getopt(argc, argv, "nt:")) != \-1) {
445 switch (opt) {
446 case \(aqn\(aq:
447 flags = 1;
448 break;
449 case \(aqt\(aq:
450 nsecs = atoi(optarg);
451 tfnd = 1;
452 break;
453 default: /* \(aq?\(aq */
454 fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en",
455 argv[0]);
456 exit(EXIT_FAILURE);
457 }
458 }
459
460 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\en",
461 flags, tfnd, nsecs, optind);
462
463 if (optind >= argc) {
464 fprintf(stderr, "Expected argument after options\en");
465 exit(EXIT_FAILURE);
466 }
467
468 printf("name argument = %s\en", argv[optind]);
469
470 /* Other code omitted */
471
472 exit(EXIT_SUCCESS);
473 }
474 .EE
475 .SS getopt_long()
476 The following example program illustrates the use of
477 .BR getopt_long ()
478 with most of its features.
479 .PP
480 .EX
481 #include <stdio.h> /* for printf */
482 #include <stdlib.h> /* for exit */
483 #include <getopt.h>
484
485 int
486 main(int argc, char *argv[])
487 {
488 int c;
489 int digit_optind = 0;
490
491 while (1) {
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 },
501 {0, 0, 0, 0 }
502 };
503
504 c = getopt_long(argc, argv, "abc:d:012",
505 long_options, &option_index);
506 if (c == \-1)
507 break;
508
509 switch (c) {
510 case 0:
511 printf("option %s", long_options[option_index].name);
512 if (optarg)
513 printf(" with arg %s", optarg);
514 printf("\en");
515 break;
516
517 case \(aq0\(aq:
518 case \(aq1\(aq:
519 case \(aq2\(aq:
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);
524 break;
525
526 case \(aqa\(aq:
527 printf("option a\en");
528 break;
529
530 case \(aqb\(aq:
531 printf("option b\en");
532 break;
533
534 case \(aqc\(aq:
535 printf("option c with value \(aq%s\(aq\en", optarg);
536 break;
537
538 case \(aqd\(aq:
539 printf("option d with value \(aq%s\(aq\en", optarg);
540 break;
541
542 case \(aq?\(aq:
543 break;
544
545 default:
546 printf("?? getopt returned character code 0%o ??\en", c);
547 }
548 }
549
550 if (optind < argc) {
551 printf("non\-option ARGV\-elements: ");
552 while (optind < argc)
553 printf("%s ", argv[optind++]);
554 printf("\en");
555 }
556
557 exit(EXIT_SUCCESS);
558 }
559 .EE
560 .SH SEE ALSO
561 .BR getopt (1),
562 .BR getsubopt (3)