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