OSDN Git Service

15c8e9bd9e985c3ae50462816dcaa40e0a35a350
[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  2010-11-01 "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 The following trivial example program uses
378 .BR getopt ()
379 to handle two program options:
380 .IR \-n ,
381 with no associated value; and
382 .IR "\-t val" ,
383 which expects an associated value.
384 .nf
385 .sp
386 #include <unistd.h>
387 #include <stdlib.h>
388 #include <stdio.h>
389
390 int
391 main(int argc, char *argv[])
392 {
393     int flags, opt;
394     int nsecs, tfnd;
395
396     nsecs = 0;
397     tfnd = 0;
398     flags = 0;
399     while ((opt = getopt(argc, argv, "nt:")) != \-1) {
400         switch (opt) {
401         case \(aqn\(aq:
402             flags = 1;
403             break;
404         case \(aqt\(aq:
405             nsecs = atoi(optarg);
406             tfnd = 1;
407             break;
408         default: /* \(aq?\(aq */
409             fprintf(stderr, "Usage: %s [\-t nsecs] [\-n] name\\n",
410                     argv[0]);
411             exit(EXIT_FAILURE);
412         }
413     }
414
415     printf("flags=%d; tfnd=%d; optind=%d\\n", flags, tfnd, optind);
416
417     if (optind >= argc) {
418         fprintf(stderr, "Expected argument after options\\n");
419         exit(EXIT_FAILURE);
420     }
421
422     printf("name argument = %s\\n", argv[optind]);
423
424     /* Other code omitted */
425
426     exit(EXIT_SUCCESS);
427 }
428 .fi
429 .PP
430 The following example program illustrates the use of
431 .BR getopt_long ()
432 with most of its features.
433 .nf
434 .sp
435 #include <stdio.h>     /* for printf */
436 #include <stdlib.h>    /* for exit */
437 #include <getopt.h>
438
439 int
440 main(int argc, char **argv)
441 {
442     int c;
443     int digit_optind = 0;
444
445     while (1) {
446         int this_option_optind = optind ? optind : 1;
447         int option_index = 0;
448         static struct option long_options[] = {
449             {"add",     required_argument, 0,  0 },
450             {"append",  no_argument,       0,  0 },
451             {"delete",  required_argument, 0,  0 },
452             {"verbose", no_argument,       0,  0 },
453             {"create",  required_argument, 0, \(aqc\(aq},
454             {"file",    required_argument, 0,  0 },
455             {0,         0,                 0,  0 }
456         };
457
458         c = getopt_long(argc, argv, "abc:d:012",
459                  long_options, &option_index);
460         if (c == \-1)
461             break;
462
463         switch (c) {
464         case 0:
465             printf("option %s", long_options[option_index].name);
466             if (optarg)
467                 printf(" with arg %s", optarg);
468             printf("\\n");
469             break;
470
471         case \(aq0\(aq:
472         case \(aq1\(aq:
473         case \(aq2\(aq:
474             if (digit_optind != 0 && digit_optind != this_option_optind)
475               printf("digits occur in two different argv\-elements.\\n");
476             digit_optind = this_option_optind;
477             printf("option %c\\n", c);
478             break;
479
480         case \(aqa\(aq:
481             printf("option a\\n");
482             break;
483
484         case \(aqb\(aq:
485             printf("option b\\n");
486             break;
487
488         case \(aqc\(aq:
489             printf("option c with value \(aq%s\(aq\\n", optarg);
490             break;
491
492         case \(aqd\(aq:
493             printf("option d with value \(aq%s\(aq\\n", optarg);
494             break;
495
496         case \(aq?\(aq:
497             break;
498
499         default:
500             printf("?? getopt returned character code 0%o ??\\n", c);
501         }
502     }
503
504     if (optind < argc) {
505         printf("non\-option ARGV\-elements: ");
506         while (optind < argc)
507             printf("%s ", argv[optind++]);
508         printf("\\n");
509     }
510
511     exit(EXIT_SUCCESS);
512 }
513 .fi
514 .SH SEE ALSO
515 .BR getsubopt (3)
516 .SH COLOPHON
517 This page is part of release 3.64 of the Linux
518 .I man-pages
519 project.
520 A description of the project,
521 and information about reporting bugs,
522 can be found at
523 \%http://www.kernel.org/doc/man\-pages/.