Debian Codegraph @

upstream/fedora-44/man3/getopt.3

raw
1 '\" t
2 .\" Copyright (c) 1993 by Thomas Koenig ([email protected])
3 .\" and Copyright 2006-2008, Michael Kerrisk <[email protected]>
4 .\"
5 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
6 .\"
7 .\" Modified Sat Jul 24 19:27:50 1993 by Rik Faith ([email protected])
8 .\" Modified Mon Aug 30 22:02:34 1995 by Jim Van Zandt <[email protected]>
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 ([email protected])
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 <[email protected]>
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 2024-12-19 "Linux man-pages 6.13"
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>
33 .P
34 .BI "int getopt(int " argc ", char *" argv [],
35 .BI " const char *" optstring );
36 .P
37 .BI "extern char *" optarg ;
38 .BI "extern int " optind ", " opterr ", " optopt ;
39 .P
40 .B #include <getopt.h>
41 .P
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
49 .P
50 .RS -4
51 Feature Test Macro Requirements for glibc (see
52 .BR feature_test_macros (7)):
53 .RE
54 .P
55 .BR getopt ():
56 .nf
57 _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
58 .fi
59 .P
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.
81 If
82 .BR getopt ()
83 is called repeatedly, it returns successively each of the option characters
84 from each of the option elements.
85 .P
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.
94 .P
95 If
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 ()
101 can
102 resume the scan with the following option character or
103 \fIargv\fP-element.
104 .P
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.
110 .P
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.
129 If
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.
142 .P
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.
156 If
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.
169 .P
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.
206 .\"
207 .SS getopt_long() and getopt_long_only()
208 The
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
221 or
222 .BR "\-\-arg param" .
223 .P
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>
229 as
230 .P
231 .in +4n
232 .EX
233 struct option {
234 const char *name;
235 int has_arg;
236 int *flag;
237 int val;
238 };
239 .EE
240 .in
241 .P
242 The meanings of the different fields are:
243 .TP
244 .I name
245 is the name of the long option.
246 .TP
247 .I has_arg
248 is:
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.
252 .TP
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.
266 .TP
267 \fIval\fP
268 is the value to return, or to load into the variable pointed
269 to by \fIflag\fP.
270 .P
271 The last element of the array has to be filled with zeros.
272 .P
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 .
276 .P
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.
292 If
293 .BR getopt ()
294 encounters an option character that was not in
295 .IR optstring ,
296 then \[aq]?\[aq] is returned.
297 If
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.
304 .P
305 .BR getopt_long ()
306 and
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
317 .TP
318 .B POSIXLY_CORRECT
319 If this is set, then option processing stops as soon as a nonoption
320 argument is encountered.
321 .SH ATTRIBUTES
322 For an explanation of the terms used in this section, see
323 .BR attributes (7).
324 .TS
325 allbox;
326 lb lb lbx
327 l l l.
328 Interface Attribute Value
329 T{
330 .na
331 .nh
332 .BR getopt (),
333 .BR getopt_long (),
334 .BR getopt_long_only ()
335 T} Thread safety T{
336 .na
337 .nh
338 MT-Unsafe race:getopt env
339 T}
340 .TE
341 .SH VERSIONS
342 POSIX specifies that the
343 .I argv
344 array argument should be
345 .IR const ,
346 but these functions permute its elements
347 unless the environment variable
348 .B POSIXLY_CORRECT
349 is set.
350 .I const
351 is used in the actual prototype to be compatible with other systems;
352 however, this page doesn't show the qualifier,
353 to avoid confusing readers.
354 .SH STANDARDS
355 .TP
356 .BR getopt ()
357 POSIX.1-2008.
358 .TP
359 .BR getopt_long ()
360 .TQ
361 .BR getopt_long_only ()
362 GNU.
363 .IP
364 The use of \[aq]+\[aq] and \[aq]\-\[aq] in
365 .I optstring
366 is a GNU extension.
367 .SH HISTORY
368 .TP
369 .BR getopt ()
370 POSIX.1-2001, and POSIX.2.
371 .P
372 On some older implementations,
373 .BR getopt ()
374 was declared in
375 .IR <stdio.h> .
376 SUSv1 permitted the declaration to appear in either
377 .I <unistd.h>
378 or
379 .IR <stdio.h> .
380 POSIX.1-1996 marked the use of
381 .I <stdio.h>
382 for this purpose as LEGACY.
383 POSIX.1-2001 does not require the declaration to appear in
384 .IR <stdio.h> .
385 .P
386 Very old versions of glibc were affected by a
387 .UR https://\:sourceware.org/\:git/\:?p=glibc.git;a=commitdiff;h=bf079e19f50d64aa5e05
388 .BI _ PID _GNU_nonoption_argv_flags_
389 environment variable
390 .UE .
391 .SH NOTES
392 A program that scans multiple argument vectors,
393 or rescans the same vector more than once,
394 and wants to make use of GNU extensions such as \[aq]+\[aq]
395 and \[aq]\-\[aq] at the start of
396 .IR optstring ,
397 or changes the value of
398 .B POSIXLY_CORRECT
399 between scans,
400 must reinitialize
401 .BR getopt ()
402 by resetting
403 .I optind
404 to 0, rather than the traditional value of 1.
405 (Resetting to 0 forces the invocation of an internal initialization
406 routine that rechecks
407 .B POSIXLY_CORRECT
408 and checks for GNU extensions in
409 .IR optstring .)
410 .P
411 Command-line arguments are parsed in strict order
412 meaning that an option requiring an argument will consume the next argument,
413 regardless of whether that argument is the correctly specified option argument
414 or simply the next option
415 (in the scenario the user mis-specifies the command line).
416 For example, if
417 .I optstring
418 is specified as "1n:"
419 and the user specifies the command line arguments incorrectly as
420 .IR "prog\ \-n\ \-1" ,
421 the
422 .I \-n
423 option will be given the
424 .B optarg
425 value "\-1", and the
426 .I \-1
427 option will be considered to have not been specified.
428 .SH EXAMPLES
429 .SS getopt()
430 The following trivial example program uses
431 .BR getopt ()
432 to handle two program options:
433 .IR \-n ,
434 with no associated value; and
435 .IR "\-t val" ,
436 which expects an associated value.
437 .P
438 .\" SRC BEGIN (getopt.c)
439 .EX
440 #include <stdio.h>
441 #include <stdlib.h>
442 #include <unistd.h>
443 \&
444 int
445 main(int argc, char *argv[])
446 {
447 int flags, opt;
448 int nsecs, tfnd;
449 \&
450 nsecs = 0;
451 tfnd = 0;
452 flags = 0;
453 while ((opt = getopt(argc, argv, "nt:")) != \-1) {
454 switch (opt) {
455 case \[aq]n\[aq]:
456 flags = 1;
457 break;
458 case \[aq]t\[aq]:
459 nsecs = atoi(optarg);
460 tfnd = 1;
461 break;
462 default: /* \[aq]?\[aq] */
463 fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\[rs]n",
464 argv[0]);
465 exit(EXIT_FAILURE);
466 }
467 }
468 \&
469 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\[rs]n",
470 flags, tfnd, nsecs, optind);
471 \&
472 if (optind >= argc) {
473 fprintf(stderr, "Expected argument after options\[rs]n");
474 exit(EXIT_FAILURE);
475 }
476 \&
477 printf("name argument = %s\[rs]n", argv[optind]);
478 \&
479 /* Other code omitted */
480 \&
481 exit(EXIT_SUCCESS);
482 }
483 .EE
484 .\" SRC END
485 .SS getopt_long()
486 The following example program illustrates the use of
487 .BR getopt_long ()
488 with most of its features.
489 .P
490 .\" SRC BEGIN (getopt_long.c)
491 .EX
492 #include <getopt.h>
493 #include <stdio.h> /* for printf */
494 #include <stdlib.h> /* for exit */
495 \&
496 int
497 main(int argc, char *argv[])
498 {
499 int c;
500 int digit_optind = 0;
501 \&
502 while (1) {
503 int this_option_optind = optind ? optind : 1;
504 int option_index = 0;
505 static struct option long_options[] = {
506 {"add", required_argument, 0, 0 },
507 {"append", no_argument, 0, 0 },
508 {"delete", required_argument, 0, 0 },
509 {"verbose", no_argument, 0, 0 },
510 {"create", required_argument, 0, \[aq]c\[aq]},
511 {"file", required_argument, 0, 0 },
512 {0, 0, 0, 0 }
513 };
514 \&
515 c = getopt_long(argc, argv, "abc:d:012",
516 long_options, &option_index);
517 if (c == \-1)
518 break;
519 \&
520 switch (c) {
521 case 0:
522 printf("option %s", long_options[option_index].name);
523 if (optarg)
524 printf(" with arg %s", optarg);
525 printf("\[rs]n");
526 break;
527 \&
528 case \[aq]0\[aq]:
529 case \[aq]1\[aq]:
530 case \[aq]2\[aq]:
531 if (digit_optind != 0 && digit_optind != this_option_optind)
532 printf("digits occur in two different argv\-elements.\[rs]n");
533 digit_optind = this_option_optind;
534 printf("option %c\[rs]n", c);
535 break;
536 \&
537 case \[aq]a\[aq]:
538 printf("option a\[rs]n");
539 break;
540 \&
541 case \[aq]b\[aq]:
542 printf("option b\[rs]n");
543 break;
544 \&
545 case \[aq]c\[aq]:
546 printf("option c with value \[aq]%s\[aq]\[rs]n", optarg);
547 break;
548 \&
549 case \[aq]d\[aq]:
550 printf("option d with value \[aq]%s\[aq]\[rs]n", optarg);
551 break;
552 \&
553 case \[aq]?\[aq]:
554 break;
555 \&
556 default:
557 printf("?? getopt returned character code 0%o ??\[rs]n", c);
558 }
559 }
560 \&
561 if (optind < argc) {
562 printf("non\-option ARGV\-elements: ");
563 while (optind < argc)
564 printf("%s ", argv[optind++]);
565 printf("\[rs]n");
566 }
567 \&
568 exit(EXIT_SUCCESS);
569 }
570 .EE
571 .\" SRC END
572 .SH SEE ALSO
573 .BR getopt (1),
574 .BR getsubopt (3)