OSDN Git Service

ddb8ed1a0d661362004fcc1fa7ec6e72c8a1b9b8
[linuxjm/LDP_man-pages.git] / original / 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  2014-05-09 "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 .sp
49 .BI "int getopt(int " argc ", char * const " argv[] ,
50 .BI "           const char *" optstring );
51 .sp
52 .BI "extern char *" optarg ;
53 .BI "extern int " optind ", " opterr ", " optopt ;
54 .sp
55 .B #include <getopt.h>
56 .sp
57 .BI "int getopt_long(int " argc ", char * const " argv[] ,
58 .BI "           const char *" optstring ,
59 .BI "           const struct option *" longopts ", int *" longindex );
60 .sp
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 .sp
66 .in -4n
67 Feature Test Macro Requirements for glibc (see
68 .BR feature_test_macros (7)):
69 .ad l
70 .in
71 .sp
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 If
171 .BR getopt ()
172 does not recognize an option character, it prints an
173 error message to \fIstderr\fP, stores the character in \fIoptopt\fP, and
174 returns \(aq?\(aq.
175 The calling program may prevent the error message by
176 setting \fIopterr\fP to 0.
177 .PP
178 If
179 .BR getopt ()
180 finds an option character in \fIargv\fP that was not
181 included in \fIoptstring\fP, or if it detects a missing option argument,
182 it returns \(aq?\(aq and sets the external variable \fIoptopt\fP to the
183 actual option character.
184 If the first character
185 (following any optional \(aq+\(aq or \(aq\-\(aq described above)
186 of \fIoptstring\fP
187 is a colon (\(aq:\(aq), then
188 .BR getopt ()
189 returns \(aq:\(aq instead of \(aq?\(aq to
190 indicate a missing option argument.
191 If an error was detected, and
192 the first character of \fIoptstring\fP is not a colon, and
193 the external variable \fIopterr\fP is nonzero (which is the default),
194 .BR getopt ()
195 prints an error message.
196 .SS getopt_long() and getopt_long_only()
197 The
198 .BR getopt_long ()
199 function works like
200 .BR getopt ()
201 except that it also accepts long options, started with two dashes.
202 (If the program accepts only long options, then
203 .I optstring
204 should be specified as an empty string (""), not NULL.)
205 Long option names may be abbreviated if the abbreviation is
206 unique or is an exact match for some defined option.
207 A long option
208 may take a parameter, of the form
209 .B \-\-arg=param
210 or
211 .BR "\-\-arg param" .
212 .PP
213 .I longopts
214 is a pointer to the first element of an array of
215 .I struct option
216 declared in
217 .I <getopt.h>
218 as
219 .in +4n
220 .nf
221 .sp
222 struct option {
223     const char *name;
224     int         has_arg;
225     int        *flag;
226     int         val;
227 };
228 .fi
229 .in
230 .PP
231 The meanings of the different fields are:
232 .TP
233 .I name
234 is the name of the long option.
235 .TP
236 .I has_arg
237 is:
238 \fBno_argument\fP (or 0) if the option does not take an argument;
239 \fBrequired_argument\fP (or 1) if the option requires an argument; or
240 \fBoptional_argument\fP (or 2) if the option takes an optional argument.
241 .TP
242 .I flag
243 specifies how results are returned for a long option.
244 If \fIflag\fP
245 is NULL, then
246 .BR getopt_long ()
247 returns \fIval\fP.
248 (For example, the calling program may set \fIval\fP to the equivalent short
249 option character.)
250 Otherwise,
251 .BR getopt_long ()
252 returns 0, and
253 \fIflag\fP points to a variable which is set to \fIval\fP if the
254 option is found, but left unchanged if the option is not found.
255 .TP
256 \fIval\fP
257 is the value to return, or to load into the variable pointed
258 to by \fIflag\fP.
259 .PP
260 The last element of the array has to be filled with zeros.
261 .PP
262 If \fIlongindex\fP is not NULL, it
263 points to a variable which is set to the index of the long option relative to
264 .IR longopts .
265 .PP
266 .BR getopt_long_only ()
267 is like
268 .BR getopt_long (),
269 but \(aq\-\(aq as well
270 as "\-\-" can indicate a long option.
271 If an option that starts with \(aq\-\(aq
272 (not "\-\-") doesn't match a long option, but does match a short option,
273 it is parsed as a short option instead.
274 .SH RETURN VALUE
275 If an option was successfully found, then
276 .BR getopt ()
277 returns the option character.
278 If all command-line options have been parsed, then
279 .BR getopt ()
280 returns \-1.
281 If
282 .BR getopt ()
283 encounters an option character that was not in
284 .IR optstring ,
285 then \(aq?\(aq is returned.
286 If
287 .BR getopt ()
288 encounters an option with a missing argument,
289 then the return value depends on the first character in
290 .IR optstring :
291 if it is \(aq:\(aq, then \(aq:\(aq is returned; otherwise \(aq?\(aq is returned.
292 .PP
293 .BR getopt_long ()
294 and
295 .BR getopt_long_only ()
296 also return the option
297 character when a short option is recognized.
298 For a long option, they
299 return \fIval\fP if \fIflag\fP is NULL, and 0 otherwise.
300 Error and \-1 returns are the same as for
301 .BR getopt (),
302 plus \(aq?\(aq for an
303 ambiguous match or an extraneous parameter.
304 .SH ENVIRONMENT
305 .TP
306 .B POSIXLY_CORRECT
307 If this is set, then option processing stops as soon as a nonoption
308 argument is encountered.
309 .TP
310 .B _<PID>_GNU_nonoption_argv_flags_
311 This variable was used by
312 .BR bash (1)
313 2.0 to communicate to glibc which arguments are the results of
314 wildcard expansion and so should not be considered as options.
315 This behavior was removed in
316 .BR bash (1)
317 version 2.01, but the support remains in glibc.
318 .SH CONFORMING TO
319 .TP
320 .BR getopt ():
321 POSIX.2 and POSIX.1-2001,
322 provided the environment variable
323 .B POSIXLY_CORRECT
324 is set.
325 Otherwise, the elements of \fIargv\fP aren't really const, because we
326 permute them.
327 We pretend they're const in the prototype to be
328 compatible with other systems.
329
330 The use of \(aq+\(aq and \(aq\-\(aq in
331 .I optstring
332 is a GNU extension.
333
334 On some older implementations,
335 .BR getopt ()
336 was declared in
337 .IR <stdio.h> .
338 SUSv1 permitted the declaration to appear in either
339 .I <unistd.h>
340 or
341 .IR <stdio.h> .
342 POSIX.1-2001 marked the use of
343 .I <stdio.h>
344 for this purpose as LEGACY.
345 POSIX.1-2001 does not allow the declaration to appear in
346 .IR <stdio.h> .
347 .TP
348 .BR getopt_long "() and " getopt_long_only ():
349 These functions are GNU extensions.
350 .SH NOTES
351 A program that scans multiple argument vectors,
352 or rescans the same vector more than once,
353 and wants to make use of GNU extensions such as \(aq+\(aq
354 and \(aq\-\(aq at the start of
355 .IR optstring ,
356 or changes the value of
357 .B POSIXLY_CORRECT
358 between scans,
359 must reinitialize
360 .BR getopt ()
361 by resetting
362 .I optind
363 to 0, rather than the traditional value of 1.
364 (Resetting to 0 forces the invocation of an internal initialization
365 routine that rechecks
366 .B POSIXLY_CORRECT
367 and checks for GNU extensions in
368 .IR optstring .)
369 .SH BUGS
370 The POSIX.2 specification of
371 .BR getopt ()
372 has a technical error described in POSIX.2 Interpretation 150.
373 The GNU
374 implementation (and probably all other implementations) implements the
375 correct behavior rather than that specified.
376 .SH EXAMPLE
377 .SS getopt()
378 The following trivial example program uses
379 .BR getopt ()
380 to handle two program options:
381 .IR \-n ,
382 with no associated value; and
383 .IR "\-t val" ,
384 which expects an associated value.
385 .nf
386 .sp
387 #include <unistd.h>
388 #include <stdlib.h>
389 #include <stdio.h>
390
391 int
392 main(int argc, char *argv[])
393 {
394     int flags, opt;
395     int nsecs, tfnd;
396
397     nsecs = 0;
398     tfnd = 0;
399     flags = 0;
400     while ((opt = getopt(argc, argv, "nt:")) != \-1) {
401         switch (opt) {
402         case \(aqn\(aq:
403             flags = 1;
404             break;
405         case \(aqt\(aq:
406             nsecs = atoi(optarg);
407             tfnd = 1;
408             break;
409         default: /* \(aq?\(aq */
410             fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\\n",
411                     argv[0]);
412             exit(EXIT_FAILURE);
413         }
414     }
415
416     printf("flags=%d; tfnd=%d; optind=%d\\n", flags, tfnd, optind);
417
418     if (optind >= argc) {
419         fprintf(stderr, "Expected argument after options\\n");
420         exit(EXIT_FAILURE);
421     }
422
423     printf("name argument = %s\\n", argv[optind]);
424
425     /* Other code omitted */
426
427     exit(EXIT_SUCCESS);
428 }
429 .fi
430 .SS getopt_long()
431 The following example program illustrates the use of
432 .BR getopt_long ()
433 with most of its features.
434 .nf
435 .sp
436 #include <stdio.h>     /* for printf */
437 #include <stdlib.h>    /* for exit */
438 #include <getopt.h>
439
440 int
441 main(int argc, char **argv)
442 {
443     int c;
444     int digit_optind = 0;
445
446     while (1) {
447         int this_option_optind = optind ? optind : 1;
448         int option_index = 0;
449         static struct option long_options[] = {
450             {"add",     required_argument, 0,  0 },
451             {"append",  no_argument,       0,  0 },
452             {"delete",  required_argument, 0,  0 },
453             {"verbose", no_argument,       0,  0 },
454             {"create",  required_argument, 0, \(aqc\(aq},
455             {"file",    required_argument, 0,  0 },
456             {0,         0,                 0,  0 }
457         };
458
459         c = getopt_long(argc, argv, "abc:d:012",
460                  long_options, &option_index);
461         if (c == \-1)
462             break;
463
464         switch (c) {
465         case 0:
466             printf("option %s", long_options[option_index].name);
467             if (optarg)
468                 printf(" with arg %s", optarg);
469             printf("\\n");
470             break;
471
472         case \(aq0\(aq:
473         case \(aq1\(aq:
474         case \(aq2\(aq:
475             if (digit_optind != 0 && digit_optind != this_option_optind)
476               printf("digits occur in two different argv\-elements.\\n");
477             digit_optind = this_option_optind;
478             printf("option %c\\n", c);
479             break;
480
481         case \(aqa\(aq:
482             printf("option a\\n");
483             break;
484
485         case \(aqb\(aq:
486             printf("option b\\n");
487             break;
488
489         case \(aqc\(aq:
490             printf("option c with value \(aq%s\(aq\\n", optarg);
491             break;
492
493         case \(aqd\(aq:
494             printf("option d with value \(aq%s\(aq\\n", optarg);
495             break;
496
497         case \(aq?\(aq:
498             break;
499
500         default:
501             printf("?? getopt returned character code 0%o ??\\n", c);
502         }
503     }
504
505     if (optind < argc) {
506         printf("non\-option ARGV\-elements: ");
507         while (optind < argc)
508             printf("%s ", argv[optind++]);
509         printf("\\n");
510     }
511
512     exit(EXIT_SUCCESS);
513 }
514 .fi
515 .SH SEE ALSO
516 .BR getsubopt (3)
517 .SH COLOPHON
518 This page is part of release 3.67 of the Linux
519 .I man-pages
520 project.
521 A description of the project,
522 information about reporting bugs,
523 and the latest version of this page,
524 can be found at
525 \%http://www.kernel.org/doc/man\-pages/.