1GETOPT(3) Linux Programmer's Manual GETOPT(3)
2
3
4
6 getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt -
7 Parse command-line options
8
10 #include <unistd.h>
11
12 int getopt(int argc, char *const argv[],
13 const char *optstring);
14
15 extern char *optarg;
16 extern int optind, opterr, optopt;
17
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 int getopt_long_only(int argc, char *const argv[],
24 const char *optstring,
25 const struct option *longopts, int *longindex);
26
27 Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
28
29 getopt():
30 _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
31
32 getopt_long(), getopt_long_only():
33 _GNU_SOURCE
34
36 The getopt() function parses the command-line arguments. Its arguments
37 argc and argv are the argument count and array as passed to the main()
38 function on program invocation. An element of argv that starts with
39 '-' (and is not exactly "-" or "--") is an option element. The charac‐
40 ters of this element (aside from the initial '-') are option charac‐
41 ters. If getopt() is called repeatedly, it returns successively each
42 of the option characters from each of the option elements.
43
44 The variable optind is the index of the next element to be processed in
45 argv. The system initializes this value to 1. The caller can reset it
46 to 1 to restart scanning of the same argv, or when scanning a new argu‐
47 ment vector.
48
49 If getopt() finds another option character, it returns that character,
50 updating the external variable optind and a static variable nextchar so
51 that the next call to getopt() can resume the scan with the following
52 option character or argv-element.
53
54 If there are no more option characters, getopt() returns -1. Then
55 optind is the index in argv of the first argv-element that is not an
56 option.
57
58 optstring is a string containing the legitimate option characters. A
59 legitimate option character is any visible one byte ascii(7) character
60 (for which isgraph(3) would return nonzero) that is not '-' or ':'. If
61 such a character is followed by a colon, the option requires an argu‐
62 ment, so getopt() places a pointer to the following text in the same
63 argv-element, or the text of the following argv-element, in optarg.
64 Two colons mean an option takes an optional arg; if there is text in
65 the current argv-element (i.e., in the same word as the option name it‐
66 self, for example, "-oarg"), then it is returned in optarg, otherwise
67 optarg is set to zero. This is a GNU extension. If optstring contains
68 W followed by a semicolon, then -W foo is treated as the long option
69 --foo. (The -W option is reserved by POSIX.2 for implementation exten‐
70 sions.) This behavior is a GNU extension, not available with libraries
71 before glibc 2.
72
73 By default, getopt() permutes the contents of argv as it scans, so that
74 eventually all the nonoptions are at the end. Two other scanning modes
75 are also implemented. If the first character of optstring is '+' or
76 the environment variable POSIXLY_CORRECT is set, then option processing
77 stops as soon as a nonoption argument is encountered. If the first
78 character of optstring is '-', then each nonoption argv-element is han‐
79 dled as if it were the argument of an option with character code 1.
80 (This is used by programs that were written to expect options and other
81 argv-elements in any order and that care about the ordering of the
82 two.) The special argument "--" forces an end of option-scanning re‐
83 gardless of the scanning mode.
84
85 While processing the option list, getopt() can detect two kinds of er‐
86 rors: (1) an option character that was not specified in optstring and
87 (2) a missing option argument (i.e., an option at the end of the com‐
88 mand line without an expected argument). Such errors are handled and
89 reported as follows:
90
91 * By default, getopt() prints an error message on standard error,
92 places the erroneous option character in optopt, and returns '?' as
93 the function result.
94
95 * If the caller has set the global variable opterr to zero, then
96 getopt() does not print an error message. The caller can determine
97 that there was an error by testing whether the function return value
98 is '?'. (By default, opterr has a nonzero value.)
99
100 * If the first character (following any optional '+' or '-' described
101 above) of optstring is a colon (':'), then getopt() likewise does
102 not print an error message. In addition, it returns ':' instead of
103 '?' to indicate a missing option argument. This allows the caller
104 to distinguish the two different types of errors.
105
106 getopt_long() and getopt_long_only()
107 The getopt_long() function works like getopt() except that it also ac‐
108 cepts long options, started with two dashes. (If the program accepts
109 only long options, then optstring should be specified as an empty
110 string (""), not NULL.) Long option names may be abbreviated if the
111 abbreviation is unique or is an exact match for some defined option. A
112 long option may take a parameter, of the form --arg=param or --arg
113 param.
114
115 longopts is a pointer to the first element of an array of struct option
116 declared in <getopt.h> as
117
118 struct option {
119 const char *name;
120 int has_arg;
121 int *flag;
122 int val;
123 };
124
125 The meanings of the different fields are:
126
127 name is the name of the long option.
128
129 has_arg
130 is: no_argument (or 0) if the option does not take an argument;
131 required_argument (or 1) if the option requires an argument; or
132 optional_argument (or 2) if the option takes an optional argu‐
133 ment.
134
135 flag specifies how results are returned for a long option. If flag
136 is NULL, then getopt_long() returns val. (For example, the
137 calling program may set val to the equivalent short option char‐
138 acter.) Otherwise, getopt_long() returns 0, and flag points to
139 a variable which is set to val if the option is found, but left
140 unchanged if the option is not found.
141
142 val is the value to return, or to load into the variable pointed to
143 by flag.
144
145 The last element of the array has to be filled with zeros.
146
147 If longindex is not NULL, it points to a variable which is set to the
148 index of the long option relative to longopts.
149
150 getopt_long_only() is like getopt_long(), but '-' as well as "--" can
151 indicate a long option. If an option that starts with '-' (not "--")
152 doesn't match a long option, but does match a short option, it is
153 parsed as a short option instead.
154
156 If an option was successfully found, then getopt() returns the option
157 character. If all command-line options have been parsed, then getopt()
158 returns -1. If getopt() encounters an option character that was not in
159 optstring, then '?' is returned. If getopt() encounters an option with
160 a missing argument, then the return value depends on the first charac‐
161 ter in optstring: if it is ':', then ':' is returned; otherwise '?' is
162 returned.
163
164 getopt_long() and getopt_long_only() also return the option character
165 when a short option is recognized. For a long option, they return val
166 if flag is NULL, and 0 otherwise. Error and -1 returns are the same as
167 for getopt(), plus '?' for an ambiguous match or an extraneous parame‐
168 ter.
169
171 POSIXLY_CORRECT
172 If this is set, then option processing stops as soon as a nonop‐
173 tion argument is encountered.
174
175 _<PID>_GNU_nonoption_argv_flags_
176 This variable was used by bash(1) 2.0 to communicate to glibc
177 which arguments are the results of wildcard expansion and so
178 should not be considered as options. This behavior was removed
179 in bash(1) version 2.01, but the support remains in glibc.
180
182 For an explanation of the terms used in this section, see at‐
183 tributes(7).
184
185 ┌───────────────────┬───────────────┬──────────────────────────────────┐
186 │Interface │ Attribute │ Value │
187 ├───────────────────┼───────────────┼──────────────────────────────────┤
188 │getopt(), │ Thread safety │ MT-Unsafe race:getopt env │
189 │getopt_long(), │ │ │
190 │getopt_long_only() │ │ │
191 └───────────────────┴───────────────┴──────────────────────────────────┘
192
194 getopt():
195 POSIX.1-2001, POSIX.1-2008, and POSIX.2, provided the environ‐
196 ment variable POSIXLY_CORRECT is set. Otherwise, the elements
197 of argv aren't really const, because these functions permute
198 them. Nevertheless, const is used in the prototype to be com‐
199 patible with other systems.
200
201 The use of '+' and '-' in optstring is a GNU extension.
202
203 On some older implementations, getopt() was declared in
204 <stdio.h>. SUSv1 permitted the declaration to appear in either
205 <unistd.h> or <stdio.h>. POSIX.1-1996 marked the use of
206 <stdio.h> for this purpose as LEGACY. POSIX.1-2001 does not re‐
207 quire the declaration to appear in <stdio.h>.
208
209 getopt_long() and getopt_long_only():
210 These functions are GNU extensions.
211
213 A program that scans multiple argument vectors, or rescans the same
214 vector more than once, and wants to make use of GNU extensions such as
215 '+' and '-' at the start of optstring, or changes the value of POSIX‐
216 LY_CORRECT between scans, must reinitialize getopt() by resetting
217 optind to 0, rather than the traditional value of 1. (Resetting to 0
218 forces the invocation of an internal initialization routine that
219 rechecks POSIXLY_CORRECT and checks for GNU extensions in optstring.)
220
221 Command-line arguments are parsed in strict order meaning that an op‐
222 tion requiring an argument will consume the next argument, regardless
223 of whether that argument is the correctly specified option argument or
224 simply the next option (in the scenario the user mis-specifies the com‐
225 mand line). For example, if optstring is specified as "1n:" and the
226 user specifies the command line arguments incorrectly as prog -n -1,
227 the -n option will be given the optarg value "-1", and the -1 option
228 will be considered to have not been specified.
229
231 getopt()
232 The following trivial example program uses getopt() to handle two pro‐
233 gram options: -n, with no associated value; and -t val, which expects
234 an associated value.
235
236 #include <unistd.h>
237 #include <stdlib.h>
238 #include <stdio.h>
239
240 int
241 main(int argc, char *argv[])
242 {
243 int flags, opt;
244 int nsecs, tfnd;
245
246 nsecs = 0;
247 tfnd = 0;
248 flags = 0;
249 while ((opt = getopt(argc, argv, "nt:")) != -1) {
250 switch (opt) {
251 case 'n':
252 flags = 1;
253 break;
254 case 't':
255 nsecs = atoi(optarg);
256 tfnd = 1;
257 break;
258 default: /* '?' */
259 fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
260 argv[0]);
261 exit(EXIT_FAILURE);
262 }
263 }
264
265 printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\n",
266 flags, tfnd, nsecs, optind);
267
268 if (optind >= argc) {
269 fprintf(stderr, "Expected argument after options\n");
270 exit(EXIT_FAILURE);
271 }
272
273 printf("name argument = %s\n", argv[optind]);
274
275 /* Other code omitted */
276
277 exit(EXIT_SUCCESS);
278 }
279
280 getopt_long()
281 The following example program illustrates the use of getopt_long() with
282 most of its features.
283
284 #include <stdio.h> /* for printf */
285 #include <stdlib.h> /* for exit */
286 #include <getopt.h>
287
288 int
289 main(int argc, char **argv)
290 {
291 int c;
292 int digit_optind = 0;
293
294 while (1) {
295 int this_option_optind = optind ? optind : 1;
296 int option_index = 0;
297 static struct option long_options[] = {
298 {"add", required_argument, 0, 0 },
299 {"append", no_argument, 0, 0 },
300 {"delete", required_argument, 0, 0 },
301 {"verbose", no_argument, 0, 0 },
302 {"create", required_argument, 0, 'c'},
303 {"file", required_argument, 0, 0 },
304 {0, 0, 0, 0 }
305 };
306
307 c = getopt_long(argc, argv, "abc:d:012",
308 long_options, &option_index);
309 if (c == -1)
310 break;
311
312 switch (c) {
313 case 0:
314 printf("option %s", long_options[option_index].name);
315 if (optarg)
316 printf(" with arg %s", optarg);
317 printf("\n");
318 break;
319
320 case '0':
321 case '1':
322 case '2':
323 if (digit_optind != 0 && digit_optind != this_option_optind)
324 printf("digits occur in two different argv-elements.\n");
325 digit_optind = this_option_optind;
326 printf("option %c\n", c);
327 break;
328
329 case 'a':
330 printf("option a\n");
331 break;
332
333 case 'b':
334 printf("option b\n");
335 break;
336
337 case 'c':
338 printf("option c with value '%s'\n", optarg);
339 break;
340
341 case 'd':
342 printf("option d with value '%s'\n", optarg);
343 break;
344
345 case '?':
346 break;
347
348 default:
349 printf("?? getopt returned character code 0%o ??\n", c);
350 }
351 }
352
353 if (optind < argc) {
354 printf("non-option ARGV-elements: ");
355 while (optind < argc)
356 printf("%s ", argv[optind++]);
357 printf("\n");
358 }
359
360 exit(EXIT_SUCCESS);
361 }
362
364 getopt(1), getsubopt(3)
365
367 This page is part of release 5.12 of the Linux man-pages project. A
368 description of the project, information about reporting bugs, and the
369 latest version of this page, can be found at
370 https://www.kernel.org/doc/man-pages/.
371
372
373
374GNU 2021-03-22 GETOPT(3)