]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man3/getopt.3
system.3: ffix
[thirdparty/man-pages.git] / man3 / getopt.3
1 .\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
2 .\"
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
7 .\"
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
12 .\"
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein. The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\" %%%LICENSE_END
24 .\"
25 .\" Modified Sat Jul 24 19:27:50 1993 by Rik Faith (faith@cs.unc.edu)
26 .\" Modified Mon Aug 30 22:02:34 1995 by Jim Van Zandt <jrv@vanzandt.mv.com>
27 .\" longindex is a pointer, has_arg can take 3 values, using consistent
28 .\" names for optstring and longindex, "\n" in formats fixed. Documenting
29 .\" opterr and getopt_long_only. Clarified explanations (borrowing heavily
30 .\" from the source code).
31 .\" Modified 8 May 1998 by Joseph S. Myers (jsm28@cam.ac.uk)
32 .\" Modified 990715, aeb: changed `EOF' into `-1' since that is what POSIX
33 .\" says; moreover, EOF is not defined in <unistd.h>.
34 .\" Modified 2002-02-16, joey: added information about nonexistent
35 .\" option character and colon as first option character
36 .\" Modified 2004-07-28, Michael Kerrisk <mtk.manpages@gmail.com>
37 .\" Added text to explain how to order both '[-+]' and ':' at
38 .\" the start of optstring
39 .\" Modified 2006-12-15, mtk, Added getopt() example program.
40 .\"
41 .TH GETOPT 3 2017-09-15 "GNU" "Linux Programmer's Manual"
42 .SH NAME
43 getopt, getopt_long, getopt_long_only,
44 optarg, optind, opterr, optopt \- Parse command-line options
45 .SH SYNOPSIS
46 .nf
47 .B #include <unistd.h>
48 .PP
49 .BI "int getopt(int " argc ", char * const " argv[] ,
50 .BI " const char *" optstring );
51 .PP
52 .BI "extern char *" optarg ;
53 .BI "extern int " optind ", " opterr ", " optopt ;
54 .PP
55 .B #include <getopt.h>
56 .PP
57 .BI "int getopt_long(int " argc ", char * const " argv[] ,
58 .BI " const char *" optstring ,
59 .BI " const struct option *" longopts ", int *" longindex );
60 .PP
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 .in -4n
67 Feature Test Macro Requirements for glibc (see
68 .BR feature_test_macros (7)):
69 .ad l
70 .in
71 .PP
72 .BR getopt ():
73 _POSIX_C_SOURCE\ >=\ 2 || _XOPEN_SOURCE
74 .br
75 .BR getopt_long (),
76 .BR getopt_long_only ():
77 _GNU_SOURCE
78 .ad b
79 .SH DESCRIPTION
80 The
81 .BR getopt ()
82 function parses the command-line arguments.
83 Its arguments
84 .I argc
85 and
86 .I argv
87 are the argument count and array as passed to the
88 .IR main ()
89 function on program invocation.
90 An element of \fIargv\fP that starts with \(aq\-\(aq
91 (and is not exactly "\-" or "\-\-")
92 is an option element.
93 The characters of this element
94 (aside from the initial \(aq\-\(aq) are option characters.
95 If
96 .BR getopt ()
97 is called repeatedly, it returns successively each of the option characters
98 from each of the option elements.
99 .PP
100 The variable
101 .I optind
102 is the index of the next element to be processed in
103 .IR argv .
104 The system initializes this value to 1.
105 The caller can reset it to 1 to restart scanning of the same
106 .IR argv ,
107 or when scanning a new argument vector.
108 .PP
109 If
110 .BR getopt ()
111 finds another option character, it returns that
112 character, updating the external variable \fIoptind\fP and a static
113 variable \fInextchar\fP so that the next call to
114 .BR getopt ()
115 can
116 resume the scan with the following option character or
117 \fIargv\fP-element.
118 .PP
119 If there are no more option characters,
120 .BR getopt ()
121 returns \-1.
122 Then \fIoptind\fP is the index in \fIargv\fP of the first
123 \fIargv\fP-element that is not an option.
124 .PP
125 .I optstring
126 is a string containing the legitimate option characters.
127 If such a
128 character is followed by a colon, the option requires an argument, so
129 .BR getopt ()
130 places a pointer to the following text in the same
131 \fIargv\fP-element, or the text of the following \fIargv\fP-element, in
132 .IR optarg .
133 Two colons mean an option takes
134 an optional arg; if there is text in the current \fIargv\fP-element
135 (i.e., in the same word as the option name itself, for example, "\-oarg"),
136 then it is returned in \fIoptarg\fP, otherwise \fIoptarg\fP is set to zero.
137 This is a GNU extension.
138 If
139 .I optstring
140 contains
141 .B W
142 followed by a semicolon, then
143 .B \-W foo
144 is treated as the long option
145 .BR \-\-foo .
146 (The
147 .B \-W
148 option is reserved by POSIX.2 for implementation extensions.)
149 This behavior is a GNU extension, not available with libraries before
150 glibc 2.
151 .PP
152 By default,
153 .BR getopt ()
154 permutes the contents of \fIargv\fP as it
155 scans, so that eventually all the nonoptions are at the end.
156 Two other modes are also implemented.
157 If the first character of
158 \fIoptstring\fP is \(aq+\(aq or the environment variable
159 .B POSIXLY_CORRECT
160 is set, then option processing stops as soon as a nonoption argument is
161 encountered.
162 If the first character of \fIoptstring\fP is \(aq\-\(aq, then
163 each nonoption \fIargv\fP-element is handled as if it were the argument of
164 an option with character code 1. (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 .PP
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 .IR 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 * 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 *
186 If the caller has set the global variable
187 .IR 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 .IR opterr
195 has a nonzero value.)
196 .IP *
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 .PP
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 .PP
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 .PP
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 .PP
271 The last element of the array has to be filled with zeros.
272 .PP
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 .PP
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; otherwise \(aq?\(aq is returned.
303 .PP
304 .BR getopt_long ()
305 and
306 .BR getopt_long_only ()
307 also return the option
308 character when a short option is recognized.
309 For a long option, they
310 return \fIval\fP if \fIflag\fP is NULL, and 0 otherwise.
311 Error and \-1 returns are the same as for
312 .BR getopt (),
313 plus \(aq?\(aq for an
314 ambiguous match or an extraneous parameter.
315 .SH ENVIRONMENT
316 .TP
317 .B POSIXLY_CORRECT
318 If this is set, then option processing stops as soon as a nonoption
319 argument is encountered.
320 .TP
321 .B _<PID>_GNU_nonoption_argv_flags_
322 This variable was used by
323 .BR bash (1)
324 2.0 to communicate to glibc which arguments are the results of
325 wildcard expansion and so should not be considered as options.
326 This behavior was removed in
327 .BR bash (1)
328 version 2.01, but the support remains in glibc.
329 .SH ATTRIBUTES
330 For an explanation of the terms used in this section, see
331 .BR attributes (7).
332 .TS
333 allbox;
334 lbw24 lb lb
335 l l l.
336 Interface Attribute Value
337 T{
338 .BR getopt (),
339 .BR getopt_long (),
340 .BR getopt_long_only ()
341 T} Thread safety MT-Unsafe race:getopt env
342 .TE
343 .SH CONFORMING TO
344 .TP
345 .BR getopt ():
346 POSIX.1-2001, POSIX.1-2008, and POSIX.2,
347 provided the environment variable
348 .B POSIXLY_CORRECT
349 is set.
350 Otherwise, the elements of \fIargv\fP aren't really
351 .IR const ,
352 because we permute them.
353 We pretend they're
354 .I const
355 in the prototype to be compatible with other systems.
356 .IP
357 The use of \(aq+\(aq and \(aq\-\(aq in
358 .I optstring
359 is a GNU extension.
360 .IP
361 On some older implementations,
362 .BR getopt ()
363 was declared in
364 .IR <stdio.h> .
365 SUSv1 permitted the declaration to appear in either
366 .I <unistd.h>
367 or
368 .IR <stdio.h> .
369 POSIX.1-1996 marked the use of
370 .I <stdio.h>
371 for this purpose as LEGACY.
372 POSIX.1-2001 does not require the declaration to appear in
373 .IR <stdio.h> .
374 .TP
375 .BR getopt_long "() and " getopt_long_only ():
376 These functions are GNU extensions.
377 .SH NOTES
378 A program that scans multiple argument vectors,
379 or rescans the same vector more than once,
380 and wants to make use of GNU extensions such as \(aq+\(aq
381 and \(aq\-\(aq at the start of
382 .IR optstring ,
383 or changes the value of
384 .B POSIXLY_CORRECT
385 between scans,
386 must reinitialize
387 .BR getopt ()
388 by resetting
389 .I optind
390 to 0, rather than the traditional value of 1.
391 (Resetting to 0 forces the invocation of an internal initialization
392 routine that rechecks
393 .B POSIXLY_CORRECT
394 and checks for GNU extensions in
395 .IR optstring .)
396 .SH EXAMPLE
397 .SS getopt()
398 The following trivial example program uses
399 .BR getopt ()
400 to handle two program options:
401 .IR \-n ,
402 with no associated value; and
403 .IR "\-t val" ,
404 which expects an associated value.
405 .PP
406 .EX
407 #include <unistd.h>
408 #include <stdlib.h>
409 #include <stdio.h>
410
411 int
412 main(int argc, char *argv[])
413 {
414 int flags, opt;
415 int nsecs, tfnd;
416
417 nsecs = 0;
418 tfnd = 0;
419 flags = 0;
420 while ((opt = getopt(argc, argv, "nt:")) != \-1) {
421 switch (opt) {
422 case \(aqn\(aq:
423 flags = 1;
424 break;
425 case \(aqt\(aq:
426 nsecs = atoi(optarg);
427 tfnd = 1;
428 break;
429 default: /* \(aq?\(aq */
430 fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\\n",
431 argv[0]);
432 exit(EXIT_FAILURE);
433 }
434 }
435
436 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\\n",
437 flags, tfnd, nsecs, optind);
438
439 if (optind >= argc) {
440 fprintf(stderr, "Expected argument after options\\n");
441 exit(EXIT_FAILURE);
442 }
443
444 printf("name argument = %s\\n", argv[optind]);
445
446 /* Other code omitted */
447
448 exit(EXIT_SUCCESS);
449 }
450 .EE
451 .SS getopt_long()
452 The following example program illustrates the use of
453 .BR getopt_long ()
454 with most of its features.
455 .PP
456 .EX
457 #include <stdio.h> /* for printf */
458 #include <stdlib.h> /* for exit */
459 #include <getopt.h>
460
461 int
462 main(int argc, char **argv)
463 {
464 int c;
465 int digit_optind = 0;
466
467 while (1) {
468 int this_option_optind = optind ? optind : 1;
469 int option_index = 0;
470 static struct option long_options[] = {
471 {"add", required_argument, 0, 0 },
472 {"append", no_argument, 0, 0 },
473 {"delete", required_argument, 0, 0 },
474 {"verbose", no_argument, 0, 0 },
475 {"create", required_argument, 0, \(aqc\(aq},
476 {"file", required_argument, 0, 0 },
477 {0, 0, 0, 0 }
478 };
479
480 c = getopt_long(argc, argv, "abc:d:012",
481 long_options, &option_index);
482 if (c == \-1)
483 break;
484
485 switch (c) {
486 case 0:
487 printf("option %s", long_options[option_index].name);
488 if (optarg)
489 printf(" with arg %s", optarg);
490 printf("\\n");
491 break;
492
493 case \(aq0\(aq:
494 case \(aq1\(aq:
495 case \(aq2\(aq:
496 if (digit_optind != 0 && digit_optind != this_option_optind)
497 printf("digits occur in two different argv\-elements.\\n");
498 digit_optind = this_option_optind;
499 printf("option %c\\n", c);
500 break;
501
502 case \(aqa\(aq:
503 printf("option a\\n");
504 break;
505
506 case \(aqb\(aq:
507 printf("option b\\n");
508 break;
509
510 case \(aqc\(aq:
511 printf("option c with value \(aq%s\(aq\\n", optarg);
512 break;
513
514 case \(aqd\(aq:
515 printf("option d with value \(aq%s\(aq\\n", optarg);
516 break;
517
518 case \(aq?\(aq:
519 break;
520
521 default:
522 printf("?? getopt returned character code 0%o ??\\n", c);
523 }
524 }
525
526 if (optind < argc) {
527 printf("non\-option ARGV\-elements: ");
528 while (optind < argc)
529 printf("%s ", argv[optind++]);
530 printf("\\n");
531 }
532
533 exit(EXIT_SUCCESS);
534 }
535 .EE
536 .SH SEE ALSO
537 .BR getopt (1),
538 .BR getsubopt (3)