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