]> git.ipfire.org Git - thirdparty/man-pages.git/blame - man3/getopt.3
stdarg.3: SEE ALSO: add vprintf(3), vscanf(3), vsyslog(3)
[thirdparty/man-pages.git] / man3 / getopt.3
CommitLineData
bf5a7247 1.\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
af88b3d3 2.\" and Copyright 2006-2008, Michael Kerrisk <mtk.manpages@gmail.com>
fea681da 3.\"
93015253 4.\" %%%LICENSE_START(VERBATIM)
fea681da
MK
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.
c13182ef 13.\"
fea681da
MK
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.
c13182ef 21.\"
fea681da
MK
22.\" Formatted or processed versions of this manual, if unaccompanied by
23.\" the source, must acknowledge the copyright and authors of this work.
4b72fb64 24.\" %%%LICENSE_END
c08df37a 25.\"
fea681da
MK
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>.
f74bac5d 35.\" Modified 2002-02-16, joey: added information about nonexistent
fea681da 36.\" option character and colon as first option character
c11b1abf 37.\" Modified 2004-07-28, Michael Kerrisk <mtk.manpages@gmail.com>
fea681da
MK
38.\" Added text to explain how to order both '[-+]' and ':' at
39.\" the start of optstring
92e014f6 40.\" Modified 2006-12-15, mtk, Added getopt() example program.
fea681da 41.\"
9ba01802 42.TH GETOPT 3 2019-03-06 "GNU" "Linux Programmer's Manual"
fea681da 43.SH NAME
57db674d
MK
44getopt, getopt_long, getopt_long_only,
45optarg, optind, opterr, optopt \- Parse command-line options
fea681da
MK
46.SH SYNOPSIS
47.nf
48.B #include <unistd.h>
68e4db0a 49.PP
fea681da
MK
50.BI "int getopt(int " argc ", char * const " argv[] ,
51.BI " const char *" optstring );
68e4db0a 52.PP
fea681da
MK
53.BI "extern char *" optarg ;
54.BI "extern int " optind ", " opterr ", " optopt ;
68e4db0a 55.PP
fea681da 56.B #include <getopt.h>
68e4db0a 57.PP
fea681da
MK
58.BI "int getopt_long(int " argc ", char * const " argv[] ,
59.BI " const char *" optstring ,
60.BI " const struct option *" longopts ", int *" longindex );
68e4db0a 61.PP
fea681da
MK
62.BI "int getopt_long_only(int " argc ", char * const " argv[] ,
63.BI " const char *" optstring ,
64.BI " const struct option *" longopts ", int *" longindex );
65.fi
68e4db0a 66.PP
0f200f07
MK
67.in -4n
68Feature Test Macro Requirements for glibc (see
69.BR feature_test_macros (7)):
70.ad l
71.in
68e4db0a 72.PP
0f200f07 73.BR getopt ():
0b8ff556 74_POSIX_C_SOURCE\ >=\ 2 || _XOPEN_SOURCE
0f200f07
MK
75.br
76.BR getopt_long (),
77.BR getopt_long_only ():
78_GNU_SOURCE
79.ad b
fea681da
MK
80.SH DESCRIPTION
81The
f10e4102 82.BR getopt ()
c13182ef
MK
83function parses the command-line arguments.
84Its arguments
fea681da
MK
85.I argc
86and
87.I argv
88are the argument count and array as passed to the
63aa9df0 89.IR main ()
fea681da 90function on program invocation.
f81fb444 91An element of \fIargv\fP that starts with \(aq\-\(aq
fea681da 92(and is not exactly "\-" or "\-\-")
c13182ef
MK
93is an option element.
94The characters of this element
f81fb444 95(aside from the initial \(aq\-\(aq) are option characters.
60a90ecd
MK
96If
97.BR getopt ()
fea681da
MK
98is called repeatedly, it returns successively each of the option characters
99from each of the option elements.
100.PP
66b08231
MK
101The variable
102.I optind
103is the index of the next element to be processed in
104.IR argv .
105The system initializes this value to 1.
106The caller can reset it to 1 to restart scanning of the same
107.IR argv ,
108or when scanning a new argument vector.
109.PP
60a90ecd
MK
110If
111.BR getopt ()
112finds another option character, it returns that
fea681da 113character, updating the external variable \fIoptind\fP and a static
60a90ecd
MK
114variable \fInextchar\fP so that the next call to
115.BR getopt ()
116can
fea681da
MK
117resume the scan with the following option character or
118\fIargv\fP-element.
119.PP
60a90ecd
MK
120If there are no more option characters,
121.BR getopt ()
122returns \-1.
fea681da
MK
123Then \fIoptind\fP is the index in \fIargv\fP of the first
124\fIargv\fP-element that is not an option.
125.PP
126.I optstring
c13182ef
MK
127is a string containing the legitimate option characters.
128If such a
fea681da 129character is followed by a colon, the option requires an argument, so
60a90ecd
MK
130.BR getopt ()
131places a pointer to the following text in the same
fea681da
MK
132\fIargv\fP-element, or the text of the following \fIargv\fP-element, in
133.IR optarg .
134Two colons mean an option takes
e6bcc128 135an optional arg; if there is text in the current \fIargv\fP-element
f262c004 136(i.e., in the same word as the option name itself, for example, "\-oarg"),
e6bcc128 137then it is returned in \fIoptarg\fP, otherwise \fIoptarg\fP is set to zero.
c13182ef
MK
138This is a GNU extension.
139If
fea681da
MK
140.I optstring
141contains
142.B W
143followed by a semicolon, then
144.B \-W foo
145is treated as the long option
146.BR \-\-foo .
147(The
148.B \-W
149option is reserved by POSIX.2 for implementation extensions.)
d9bfdb9c 150This behavior is a GNU extension, not available with libraries before
5260fe08 151glibc 2.
fea681da 152.PP
60a90ecd
MK
153By default,
154.BR getopt ()
155permutes the contents of \fIargv\fP as it
24b74457 156scans, so that eventually all the nonoptions are at the end.
c13182ef
MK
157Two other modes are also implemented.
158If the first character of
f81fb444 159\fIoptstring\fP is \(aq+\(aq or the environment variable
d9a10d9d 160.B POSIXLY_CORRECT
24b74457 161is set, then option processing stops as soon as a nonoption argument is
c13182ef 162encountered.
f81fb444 163If the first character of \fIoptstring\fP is \(aq\-\(aq, then
24b74457 164each nonoption \fIargv\fP-element is handled as if it were the argument of
fea681da
MK
165an option with character code 1. (This is used by programs that were
166written to expect options and other \fIargv\fP-elements in any order
167and that care about the ordering of the two.)
168The special argument "\-\-" forces an end of option-scanning regardless
169of the scanning mode.
170.PP
a4746c39
MK
171While processing the option list,
172.BR getopt ()
173can detect two kinds of errors:
174(1) an option character that was not specified in
175.IR optstring
176and (2) a missing option argument
177(i.e., an option at the end of the command line without an expected argument).
178Such errors are handled and reported as follows:
179.IP * 3
180By default,
60a90ecd 181.BR getopt ()
a4746c39
MK
182prints an error message on standard error,
183places the erroneous option character in
184.IR optopt ,
185and returns \(aq?\(aq as the function result.
186.IP *
187If the caller has set the global variable
188.IR opterr
189to zero, then
190.BR getopt ()
191does not print an error message.
192The caller can determine that there was an error by testing whether
193the function return value is \(aq?\(aq.
194(By default,
195.IR opterr
196has a nonzero value.)
197.IP *
c13182ef 198If the first character
f81fb444 199(following any optional \(aq+\(aq or \(aq\-\(aq described above)
fea681da 200of \fIoptstring\fP
f81fb444 201is a colon (\(aq:\(aq), then
60a90ecd 202.BR getopt ()
a4746c39
MK
203likewise does not print an error message.
204In addition, it returns \(aq:\(aq instead of \(aq?\(aq to
c13182ef 205indicate a missing option argument.
a4746c39
MK
206This allows the caller to distinguish the two different types of errors.
207.\"
2aeec1f9 208.SS getopt_long() and getopt_long_only()
fea681da 209The
f10e4102 210.BR getopt_long ()
fea681da 211function works like
f10e4102 212.BR getopt ()
c1ed35a7 213except that it also accepts long options, started with two dashes.
d0ac4fb3
MK
214(If the program accepts only long options, then
215.I optstring
216should be specified as an empty string (""), not NULL.)
fea681da 217Long option names may be abbreviated if the abbreviation is
c13182ef
MK
218unique or is an exact match for some defined option.
219A long option
fea681da
MK
220may take a parameter, of the form
221.B \-\-arg=param
222or
223.BR "\-\-arg param" .
224.PP
225.I longopts
226is a pointer to the first element of an array of
8478ee02 227.I struct option
fea681da 228declared in
8478ee02 229.I <getopt.h>
fea681da 230as
bdd915e2 231.PP
088a639b 232.in +4n
b8302363 233.EX
fea681da 234struct option {
cf448976
MK
235 const char *name;
236 int has_arg;
237 int *flag;
238 int val;
fea681da 239};
b8302363 240.EE
cf448976 241.in
fea681da
MK
242.PP
243The meanings of the different fields are:
244.TP
245.I name
246is the name of the long option.
247.TP
248.I has_arg
249is:
f10e4102
MK
250\fBno_argument\fP (or 0) if the option does not take an argument;
251\fBrequired_argument\fP (or 1) if the option requires an argument; or
fea681da
MK
252\fBoptional_argument\fP (or 2) if the option takes an optional argument.
253.TP
254.I flag
c13182ef
MK
255specifies how results are returned for a long option.
256If \fIflag\fP
60a90ecd
MK
257is NULL, then
258.BR getopt_long ()
7066ef44
MK
259returns \fIval\fP.
260(For example, the calling program may set \fIval\fP to the equivalent short
c13182ef 261option character.)
60a90ecd
MK
262Otherwise,
263.BR getopt_long ()
264returns 0, and
fea681da
MK
265\fIflag\fP points to a variable which is set to \fIval\fP if the
266option is found, but left unchanged if the option is not found.
267.TP
c13182ef 268\fIval\fP
fea681da
MK
269is the value to return, or to load into the variable pointed
270to by \fIflag\fP.
271.PP
7b01461a 272The last element of the array has to be filled with zeros.
fea681da 273.PP
35e21ba7 274If \fIlongindex\fP is not NULL, it
fea681da
MK
275points to a variable which is set to the index of the long option relative to
276.IR longopts .
277.PP
60a90ecd
MK
278.BR getopt_long_only ()
279is like
280.BR getopt_long (),
f81fb444 281but \(aq\-\(aq as well
f8a07a21 282as "\-\-" can indicate a long option.
f81fb444 283If an option that starts with \(aq\-\(aq
f8a07a21 284(not "\-\-") doesn't match a long option, but does match a short option,
c13182ef 285it is parsed as a short option instead.
47297adb 286.SH RETURN VALUE
f10e4102
MK
287If an option was successfully found, then
288.BR getopt ()
289returns the option character.
290If all command-line options have been parsed, then
291.BR getopt ()
292returns \-1.
293If
294.BR getopt ()
295encounters an option character that was not in
296.IR optstring ,
f81fb444 297then \(aq?\(aq is returned.
f10e4102
MK
298If
299.BR getopt ()
300encounters an option with a missing argument,
301then the return value depends on the first character in
302.IR optstring :
f81fb444 303if it is \(aq:\(aq, then \(aq:\(aq is returned; otherwise \(aq?\(aq is returned.
fea681da 304.PP
60a90ecd
MK
305.BR getopt_long ()
306and
307.BR getopt_long_only ()
308also return the option
c13182ef
MK
309character when a short option is recognized.
310For a long option, they
311return \fIval\fP if \fIflag\fP is NULL, and 0 otherwise.
60a90ecd
MK
312Error and \-1 returns are the same as for
313.BR getopt (),
f81fb444 314plus \(aq?\(aq for an
fea681da 315ambiguous match or an extraneous parameter.
d219a1a3 316.SH ENVIRONMENT
fea681da 317.TP
fea681da 318.B POSIXLY_CORRECT
24b74457 319If this is set, then option processing stops as soon as a nonoption
fea681da
MK
320argument is encountered.
321.TP
fea681da
MK
322.B _<PID>_GNU_nonoption_argv_flags_
323This variable was used by
f19a0f03 324.BR bash (1)
5260fe08 3252.0 to communicate to glibc which arguments are the results of
c13182ef 326wildcard expansion and so should not be considered as options.
d9bfdb9c 327This behavior was removed in
f19a0f03 328.BR bash (1)
5260fe08 329version 2.01, but the support remains in glibc.
c7401a75
PH
330.SH ATTRIBUTES
331For an explanation of the terms used in this section, see
332.BR attributes (7).
333.TS
334allbox;
335lbw24 lb lb
336l l l.
337Interface Attribute Value
338T{
339.BR getopt (),
340.BR getopt_long (),
341.BR getopt_long_only ()
5eef415b 342T} Thread safety MT-Unsafe race:getopt env
c7401a75 343.TE
47297adb 344.SH CONFORMING TO
2b2581ee
MK
345.TP
346.BR getopt ():
88490b86 347POSIX.1-2001, POSIX.1-2008, and POSIX.2,
d9a10d9d
MK
348provided the environment variable
349.B POSIXLY_CORRECT
350is set.
1e3ae1b4
MK
351Otherwise, the elements of \fIargv\fP aren't really
352.IR const ,
45c2b89b
MK
353because these functions permute them.
354Nevertheless,
1e3ae1b4 355.I const
45c2b89b 356is used in the prototype to be compatible with other systems.
847e0d88 357.IP
e94c735e
MK
358The use of \(aq+\(aq and \(aq\-\(aq in
359.I optstring
360is a GNU extension.
847e0d88 361.IP
2b2581ee
MK
362On some older implementations,
363.BR getopt ()
364was declared in
365.IR <stdio.h> .
366SUSv1 permitted the declaration to appear in either
367.I <unistd.h>
368or
369.IR <stdio.h> .
accc82d2 370POSIX.1-1996 marked the use of
2b2581ee
MK
371.I <stdio.h>
372for this purpose as LEGACY.
accc82d2 373POSIX.1-2001 does not require the declaration to appear in
2b2581ee 374.IR <stdio.h> .
e94c735e
MK
375.TP
376.BR getopt_long "() and " getopt_long_only ():
377These functions are GNU extensions.
378.SH NOTES
379A program that scans multiple argument vectors,
380or rescans the same vector more than once,
381and wants to make use of GNU extensions such as \(aq+\(aq
c2a80b76 382and \(aq\-\(aq at the start of
e94c735e
MK
383.IR optstring ,
384or changes the value of
385.B POSIXLY_CORRECT
386between scans,
387must reinitialize
388.BR getopt ()
389by resetting
390.I optind
391to 0, rather than the traditional value of 1.
392(Resetting to 0 forces the invocation of an internal initialization
393routine that rechecks
394.B POSIXLY_CORRECT
395and checks for GNU extensions in
396.IR optstring .)
fea681da 397.SH EXAMPLE
81e10454 398.SS getopt()
92e014f6
MK
399The following trivial example program uses
400.BR getopt ()
c13182ef 401to handle two program options:
f262c004 402.IR \-n ,
92e014f6 403with no associated value; and
f262c004 404.IR "\-t val" ,
92e014f6 405which expects an associated value.
bdd915e2
MK
406.PP
407.EX
92e014f6
MK
408#include <unistd.h>
409#include <stdlib.h>
410#include <stdio.h>
411
412int
413main(int argc, char *argv[])
414{
415 int flags, opt;
416 int nsecs, tfnd;
417
418 nsecs = 0;
419 tfnd = 0;
420 flags = 0;
29059a65 421 while ((opt = getopt(argc, argv, "nt:")) != \-1) {
92e014f6 422 switch (opt) {
f81fb444 423 case \(aqn\(aq:
92e014f6
MK
424 flags = 1;
425 break;
f81fb444 426 case \(aqt\(aq:
92e014f6
MK
427 nsecs = atoi(optarg);
428 tfnd = 1;
429 break;
f81fb444 430 default: /* \(aq?\(aq */
d1a71985 431 fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\en",
cec29a73 432 argv[0]);
92e014f6
MK
433 exit(EXIT_FAILURE);
434 }
435 }
436
d1a71985 437 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\en",
26f418da 438 flags, tfnd, nsecs, optind);
92e014f6
MK
439
440 if (optind >= argc) {
d1a71985 441 fprintf(stderr, "Expected argument after options\en");
92e014f6
MK
442 exit(EXIT_FAILURE);
443 }
444
d1a71985 445 printf("name argument = %s\en", argv[optind]);
92e014f6
MK
446
447 /* Other code omitted */
448
449 exit(EXIT_SUCCESS);
450}
66af361c 451.EE
81e10454 452.SS getopt_long()
fea681da 453The following example program illustrates the use of
f10e4102 454.BR getopt_long ()
fea681da 455with most of its features.
bdd915e2 456.PP
66af361c 457.EX
fea681da
MK
458#include <stdio.h> /* for printf */
459#include <stdlib.h> /* for exit */
460#include <getopt.h>
66af361c 461
fea681da 462int
c13182ef 463main(int argc, char **argv)
41798314 464{
fea681da
MK
465 int c;
466 int digit_optind = 0;
66af361c 467
fea681da
MK
468 while (1) {
469 int this_option_optind = optind ? optind : 1;
470 int option_index = 0;
471 static struct option long_options[] = {
e5266ff9
BW
472 {"add", required_argument, 0, 0 },
473 {"append", no_argument, 0, 0 },
474 {"delete", required_argument, 0, 0 },
475 {"verbose", no_argument, 0, 0 },
476 {"create", required_argument, 0, \(aqc\(aq},
477 {"file", required_argument, 0, 0 },
478 {0, 0, 0, 0 }
fea681da 479 };
66af361c 480
cf0a9ace 481 c = getopt_long(argc, argv, "abc:d:012",
fea681da
MK
482 long_options, &option_index);
483 if (c == \-1)
484 break;
66af361c 485
fea681da
MK
486 switch (c) {
487 case 0:
cf0a9ace 488 printf("option %s", long_options[option_index].name);
fea681da 489 if (optarg)
cf0a9ace 490 printf(" with arg %s", optarg);
d1a71985 491 printf("\en");
fea681da 492 break;
66af361c 493
f81fb444
MK
494 case \(aq0\(aq:
495 case \(aq1\(aq:
496 case \(aq2\(aq:
fea681da 497 if (digit_optind != 0 && digit_optind != this_option_optind)
d1a71985 498 printf("digits occur in two different argv\-elements.\en");
fea681da 499 digit_optind = this_option_optind;
d1a71985 500 printf("option %c\en", c);
fea681da 501 break;
66af361c 502
f81fb444 503 case \(aqa\(aq:
d1a71985 504 printf("option a\en");
fea681da 505 break;
66af361c 506
f81fb444 507 case \(aqb\(aq:
d1a71985 508 printf("option b\en");
fea681da 509 break;
66af361c 510
f81fb444 511 case \(aqc\(aq:
d1a71985 512 printf("option c with value \(aq%s\(aq\en", optarg);
fea681da 513 break;
66af361c 514
f81fb444 515 case \(aqd\(aq:
d1a71985 516 printf("option d with value \(aq%s\(aq\en", optarg);
fea681da 517 break;
66af361c 518
f81fb444 519 case \(aq?\(aq:
fea681da 520 break;
66af361c 521
fea681da 522 default:
d1a71985 523 printf("?? getopt returned character code 0%o ??\en", c);
fea681da
MK
524 }
525 }
66af361c 526
fea681da 527 if (optind < argc) {
29059a65 528 printf("non\-option ARGV\-elements: ");
fea681da 529 while (optind < argc)
cf0a9ace 530 printf("%s ", argv[optind++]);
d1a71985 531 printf("\en");
fea681da 532 }
66af361c 533
4c44ffe5 534 exit(EXIT_SUCCESS);
fea681da 535}
bdd915e2 536.EE
47297adb 537.SH SEE ALSO
35d82b25 538.BR getopt (1),
0a4f8b7b 539.BR getsubopt (3)