1GETOPT(3) Linux Programmer's Manual GETOPT(3)
2
3
4
6 getopt - Parse command-line options
7
9 #include <unistd.h>
10
11 int getopt(int argc, char * const argv[],
12 const char *optstring);
13
14 extern char *optarg;
15 extern int optind, opterr, optopt;
16
17 #define _GNU_SOURCE
18 #include <getopt.h>
19
20 int getopt_long(int argc, char * const argv[],
21 const char *optstring,
22 const struct option *longopts, int *longindex);
23
24 int getopt_long_only(int argc, char * const argv[],
25 const char *optstring,
26 const struct option *longopts, int *longindex);
27
29 The getopt() function parses the command-line arguments. Its arguments
30 argc and argv are the argument count and array as passed to the main()
31 function on program invocation. An element of argv that starts with
32 '-' (and is not exactly "-" or "--") is an option element. The charac‐
33 ters of this element (aside from the initial '-') are option charac‐
34 ters. If getopt() is called repeatedly, it returns successively each
35 of the option characters from each of the option elements.
36
37 If getopt() finds another option character, it returns that character,
38 updating the external variable optind and a static variable nextchar so
39 that the next call to getopt() can resume the scan with the following
40 option character or argv-element.
41
42 If there are no more option characters, getopt() returns -1. Then
43 optind is the index in argv of the first argv-element that is not an
44 option.
45
46 optstring is a string containing the legitimate option characters. If
47 such a character is followed by a colon, the option requires an argu‐
48 ment, so getopt() places a pointer to the following text in the same
49 argv-element, or the text of the following argv-element, in optarg.
50 Two colons mean an option takes an optional arg; if there is text in
51 the current argv-element (i.e., in the same word as the option name
52 itself, for example, "-oarg"), then it is returned in optarg, otherwise
53 optarg is set to zero. This is a GNU extension. If optstring contains
54 W followed by a semicolon, then -W foo is treated as the long option
55 --foo. (The -W option is reserved by POSIX.2 for implementation exten‐
56 sions.) This behaviour is a GNU extension, not available with
57 libraries before GNU libc 2.
58
59 By default, getopt() permutes the contents of argv as it scans, so that
60 eventually all the non-options are at the end. Two other modes are
61 also implemented. If the first character of optstring is '+' or the
62 environment variable POSIXLY_CORRECT is set, then option processing
63 stops as soon as a non-option argument is encountered. If the first
64 character of optstring is '-', then each non-option argv-element is
65 handled as if it were the argument of an option with character code 1.
66 (This is used by programs that were written to expect options and other
67 argv-elements in any order and that care about the ordering of the
68 two.) The special argument "--" forces an end of option-scanning
69 regardless of the scanning mode.
70
71 If getopt() does not recognize an option character, it prints an error
72 message to stderr, stores the character in optopt, and returns '?'.
73 The calling program may prevent the error message by setting opterr to
74 0.
75
76 If getopt() finds an option character in argv that was not included in
77 optstring, or if it detects a missing option argument, it returns '?'
78 and sets the external variable optopt to the actual option character.
79 If the first character (following any optional '+' or '-' described
80 above) of optstring is a colon (':'), then getopt() returns ':' instead
81 of '?' to indicate a missing option argument. If an error was
82 detected, and the first character of optstring is not a colon, and the
83 external variable opterr is non-zero (which is the default), getopt()
84 prints an error message.
85
86 The getopt_long() function works like getopt() except that it also
87 accepts long options, started out by two dashes. (If the program
88 accepts only long options, then optstring should be specified as an
89 empty string (""), not NULL.) Long option names may be abbreviated if
90 the abbreviation is unique or is an exact match for some defined
91 option. A long option may take a parameter, of the form --arg=param or
92 --arg param.
93
94 longopts is a pointer to the first element of an array of struct option
95 declared in <getopt.h> as
96
97 struct option {
98 const char *name;
99 int has_arg;
100 int *flag;
101 int val;
102 };
103
104 The meanings of the different fields are:
105
106 name is the name of the long option.
107
108 has_arg
109 is: no_argument (or 0) if the option does not take an argument;
110 required_argument (or 1) if the option requires an argument; or
111 optional_argument (or 2) if the option takes an optional argu‐
112 ment.
113
114 flag specifies how results are returned for a long option. If flag
115 is NULL, then getopt_long() returns val. (For example, the
116 calling program may set val to the equivalent short option char‐
117 acter.) Otherwise, getopt_long() returns 0, and flag points to
118 a variable which is set to val if the option is found, but left
119 unchanged if the option is not found.
120
121 val is the value to return, or to load into the variable pointed to
122 by flag.
123
124 The last element of the array has to be filled with zeroes.
125
126 If longindex is not NULL, it points to a variable which is set to the
127 index of the long option relative to longopts.
128
129 getopt_long_only() is like getopt_long(), but '-' as well as '--' can
130 indicate a long option. If an option that starts with '-' (not '--')
131 doesn't match a long option, but does match a short option, it is
132 parsed as a short option instead.
133
135 If an option was successfully found, then getopt() returns the option
136 character. If all command-line options have been parsed, then getopt()
137 returns -1. If getopt() encounters an option character that was not in
138 optstring, then '?' is returned. If getopt() encounters an option with
139 a missing argument, then the return value depends on the first charac‐
140 ter in optstring: if it is ':', then ':' is returned; otherwise '?' is
141 returned.
142
143 getopt_long() and getopt_long_only() also return the option character
144 when a short option is recognized. For a long option, they return val
145 if flag is NULL, and 0 otherwise. Error and -1 returns are the same as
146 for getopt(), plus '?' for an ambiguous match or an extraneous parame‐
147 ter.
148
150 POSIXLY_CORRECT
151 If this is set, then option processing stops as soon as a non-
152 option argument is encountered.
153
154 _<PID>_GNU_nonoption_argv_flags_
155 This variable was used by bash 2.0 to communicate to GNU libc
156 which arguments are the results of wildcard expansion and so
157 should not be considered as options. This behaviour was removed
158 in bash version 2.01, but the support remains in GNU libc.
159
161 The following trivial example program uses getopt() to handle two pro‐
162 gram options: -n, with no associated value; and -t val, which expects
163 an associated value.
164
165 #include <unistd.h>
166 #include <stdlib.h>
167 #include <stdio.h>
168
169 int
170 main(int argc, char *argv[])
171 {
172 int flags, opt;
173 int nsecs, tfnd;
174
175 nsecs = 0;
176 tfnd = 0;
177 flags = 0;
178 while ((opt = getopt(argc, argv, "nt:")) != -1) {
179 switch (opt) {
180 case 'n':
181 flags = 1;
182 break;
183 case 't':
184 nsecs = atoi(optarg);
185 tfnd = 1;
186 break;
187 default: /* '?' */
188 fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
189 argv[1]);
190 exit(EXIT_FAILURE);
191 }
192 }
193
194 printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
195
196 if (optind >= argc) {
197 fprintf(stderr, "Expected argument after options\n");
198 exit(EXIT_FAILURE);
199 }
200
201 printf("name argument = %s\n", argv[optind]);
202
203 /* Other code omitted */
204
205 exit(EXIT_SUCCESS);
206 }
207
208 The following example program illustrates the use of getopt_long() with
209 most of its features.
210
211 #include <stdio.h> /* for printf */
212 #include <stdlib.h> /* for exit */
213 #include <getopt.h>
214
215 int
216 main (int argc, char **argv) {
217 int c;
218 int digit_optind = 0;
219
220 while (1) {
221 int this_option_optind = optind ? optind : 1;
222 int option_index = 0;
223 static struct option long_options[] = {
224 {"add", 1, 0, 0},
225 {"append", 0, 0, 0},
226 {"delete", 1, 0, 0},
227 {"verbose", 0, 0, 0},
228 {"create", 1, 0, 'c'},
229 {"file", 1, 0, 0},
230 {0, 0, 0, 0}
231 };
232
233 c = getopt_long (argc, argv, "abc:d:012",
234 long_options, &option_index);
235 if (c == -1)
236 break;
237
238 switch (c) {
239 case 0:
240 printf ("option %s", long_options[option_index].name);
241 if (optarg)
242 printf (" with arg %s", optarg);
243 printf ("\n");
244 break;
245
246 case '0':
247 case '1':
248 case '2':
249 if (digit_optind != 0 && digit_optind != this_option_optind)
250 printf ("digits occur in two different argv-elements.\n");
251 digit_optind = this_option_optind;
252 printf ("option %c\n", c);
253 break;
254
255 case 'a':
256 printf ("option a\n");
257 break;
258
259 case 'b':
260 printf ("option b\n");
261 break;
262
263 case 'c':
264 printf ("option c with value '%s'\n", optarg);
265 break;
266
267 case 'd':
268 printf ("option d with value '%s'\n", optarg);
269 break;
270
271 case '?':
272 break;
273
274 default:
275 printf ("?? getopt returned character code 0%o ??\n", c);
276 }
277 }
278
279 if (optind < argc) {
280 printf ("non-option ARGV-elements: ");
281 while (optind < argc)
282 printf ("%s ", argv[optind++]);
283 printf ("\n");
284 }
285
286 exit (0);
287 }
288
290 The POSIX.2 specification of getopt() has a technical error described
291 in POSIX.2 Interpretation 150. The GNU implementation (and probably
292 all other implementations) implements the correct behaviour rather than
293 that specified.
294
296 getopt():
297 POSIX.2 and POSIX.1-2001, provided the environment variable
298 POSIXLY_CORRECT is set. Otherwise, the elements of argv aren't
299 really const, because we permute them. We pretend they're const
300 in the prototype to be compatible with other systems.
301
302 On some older implementations, getopt() was declared in
303 <stdio.h>. SUSv1 permitted the declaration to appear in either
304 <unistd.h> or <stdio.h>. POSIX.1-2001 marked the use of
305 <stdio.h> for this purpose as LEGACY. POSIX.1-2001 does not
306 allow the declaration to appear in <stdio.h>.
307
309 feature_test_macros(7)
310
311
312
313GNU 2004-07-28 GETOPT(3)