1getopt(3)                  Library Functions Manual                  getopt(3)
2
3
4

NAME

6       getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt -
7       Parse command-line options
8

LIBRARY

10       Standard C library (libc, -lc)
11

SYNOPSIS

13       #include <unistd.h>
14
15       int getopt(int argc, char *argv[],
16                  const char *optstring);
17
18       extern char *optarg;
19       extern int optind, opterr, optopt;
20
21       #include <getopt.h>
22
23       int getopt_long(int argc, char *argv[],
24                  const char *optstring,
25                  const struct option *longopts, int *longindex);
26       int getopt_long_only(int argc, char *argv[],
27                  const char *optstring,
28                  const struct option *longopts, int *longindex);
29
30   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
31
32       getopt():
33           _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE
34
35       getopt_long(), getopt_long_only():
36           _GNU_SOURCE
37

DESCRIPTION

39       The getopt() function parses the command-line arguments.  Its arguments
40       argc  and argv are the argument count and array as passed to the main()
41       function on program invocation.  An element of argv  that  starts  with
42       '-' (and is not exactly "-" or "--") is an option element.  The charac‐
43       ters of this element (aside from the initial '-')  are  option  charac‐
44       ters.   If  getopt() is called repeatedly, it returns successively each
45       of the option characters from each of the option elements.
46
47       The variable optind is the index of the next element to be processed in
48       argv.  The system initializes this value to 1.  The caller can reset it
49       to 1 to restart scanning of the same argv, or when scanning a new argu‐
50       ment vector.
51
52       If  getopt() finds another option character, it returns that character,
53       updating the external variable optind and a static variable nextchar so
54       that  the  next call to getopt() can resume the scan with the following
55       option character or argv-element.
56
57       If there are no more option  characters,  getopt()  returns  -1.   Then
58       optind  is  the  index in argv of the first argv-element that is not an
59       option.
60
61       optstring is a string containing the legitimate option  characters.   A
62       legitimate  option character is any visible one byte ascii(7) character
63       (for which isgraph(3) would return nonzero) that is not  '-',  ':',  or
64       ';'.   If  such a character is followed by a colon, the option requires
65       an argument, so getopt() places a pointer to the following text in  the
66       same  argv-element,  or  the text of the following argv-element, in op‐
67       targ.  Two colons mean an option takes an optional  arg;  if  there  is
68       text  in the current argv-element (i.e., in the same word as the option
69       name itself, for example, "-oarg"), then it is returned in optarg, oth‐
70       erwise  optarg  is set to zero.  This is a GNU extension.  If optstring
71       contains W followed by a semicolon, then -W foo is treated as the  long
72       option --foo.  (The -W option is reserved by POSIX.2 for implementation
73       extensions.)  This behavior is a GNU extension, not available with  li‐
74       braries before glibc 2.
75
76       By default, getopt() permutes the contents of argv as it scans, so that
77       eventually all the nonoptions are at the end.  Two other scanning modes
78       are  also  implemented.   If the first character of optstring is '+' or
79       the environment variable POSIXLY_CORRECT is set, then option processing
80       stops  as  soon  as a nonoption argument is encountered.  If '+' is not
81       the first character of optstring, it is treated as a normal option.  If
82       POSIXLY_CORRECT  behaviour is required in this case optstring will con‐
83       tain two '+' symbols.  If the first character of optstring is '-', then
84       each nonoption argv-element is handled as if it were the argument of an
85       option with character code 1.  (This is  used  by  programs  that  were
86       written to expect options and other argv-elements in any order and that
87       care about the ordering of the two.)  The special argument "--"  forces
88       an end of option-scanning regardless of the scanning mode.
89
90       While  processing the option list, getopt() can detect two kinds of er‐
91       rors: (1) an option character that was not specified in  optstring  and
92       (2)  a  missing option argument (i.e., an option at the end of the com‐
93       mand line without an expected argument).  Such errors are  handled  and
94       reported as follows:
95
96       •  By  default,  getopt()  prints  an  error message on standard error,
97          places the erroneous option character in optopt, and returns '?'  as
98          the function result.
99
100       •  If  the  caller  has  set  the  global variable opterr to zero, then
101          getopt() does not print an error message.  The caller can  determine
102          that there was an error by testing whether the function return value
103          is '?'.  (By default, opterr has a nonzero value.)
104
105       •  If the first character (following any optional '+' or '-'  described
106          above)  of  optstring  is a colon (':'), then getopt() likewise does
107          not print an error message.  In addition, it returns ':' instead  of
108          '?'  to  indicate a missing option argument.  This allows the caller
109          to distinguish the two different types of errors.
110
111   getopt_long() and getopt_long_only()
112       The getopt_long() function works like getopt() except that it also  ac‐
113       cepts  long  options, started with two dashes.  (If the program accepts
114       only long options, then optstring  should  be  specified  as  an  empty
115       string  (""),  not  NULL.)  Long option names may be abbreviated if the
116       abbreviation is unique or is an exact match for some defined option.  A
117       long  option  may  take  a  parameter, of the form --arg=param or --arg
118       param.
119
120       longopts is a pointer to the first element of an array of struct option
121       declared in <getopt.h> as
122
123           struct option {
124               const char *name;
125               int         has_arg;
126               int        *flag;
127               int         val;
128           };
129
130       The meanings of the different fields are:
131
132       name   is the name of the long option.
133
134       has_arg
135              is:  no_argument (or 0) if the option does not take an argument;
136              required_argument (or 1) if the option requires an argument;  or
137              optional_argument  (or  2) if the option takes an optional argu‐
138              ment.
139
140       flag   specifies how results are returned for a long option.   If  flag
141              is  NULL,  then  getopt_long()  returns  val.  (For example, the
142              calling program may set val to the equivalent short option char‐
143              acter.)   Otherwise, getopt_long() returns 0, and flag points to
144              a variable which is set to val if the option is found, but  left
145              unchanged if the option is not found.
146
147       val    is  the value to return, or to load into the variable pointed to
148              by flag.
149
150       The last element of the array has to be filled with zeros.
151
152       If longindex is not NULL, it points to a variable which is set  to  the
153       index of the long option relative to longopts.
154
155       getopt_long_only()  is  like getopt_long(), but '-' as well as "--" can
156       indicate a long option.  If an option that starts with '-'  (not  "--")
157       doesn't  match  a  long  option,  but  does match a short option, it is
158       parsed as a short option instead.
159

RETURN VALUE

161       If an option was successfully found, then getopt() returns  the  option
162       character.  If all command-line options have been parsed, then getopt()
163       returns -1.  If getopt() encounters an option character that was not in
164       optstring, then '?' is returned.  If getopt() encounters an option with
165       a missing argument, then the return value depends on the first  charac‐
166       ter  in optstring: if it is ':', then ':' is returned; otherwise '?' is
167       returned.
168
169       getopt_long() and getopt_long_only() also return the  option  character
170       when  a short option is recognized.  For a long option, they return val
171       if flag is NULL, and 0 otherwise.  Error and -1 returns are the same as
172       for  getopt(), plus '?' for an ambiguous match or an extraneous parame‐
173       ter.
174

ENVIRONMENT

176       POSIXLY_CORRECT
177              If this is set, then option processing stops as soon as a nonop‐
178              tion argument is encountered.
179
180       _<PID>_GNU_nonoption_argv_flags_
181              This  variable  was  used by bash(1) 2.0 to communicate to glibc
182              which arguments are the results of  wildcard  expansion  and  so
183              should  not be considered as options.  This behavior was removed
184              in bash(1) 2.01, but the support remains in glibc.
185

ATTRIBUTES

187       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
188       tributes(7).
189
190       ┌───────────────────┬───────────────┬──────────────────────────────────┐
191Interface          Attribute     Value                            
192       ├───────────────────┼───────────────┼──────────────────────────────────┤
193getopt(),          │ Thread safety │ MT-Unsafe race:getopt env        │
194getopt_long(),     │               │                                  │
195getopt_long_only() │               │                                  │
196       └───────────────────┴───────────────┴──────────────────────────────────┘
197

VERSIONS

199       POSIX specifies that the argv array argument should be const, but these
200       functions permute its elements unless the environment  variable  POSIX‐
201       LY_CORRECT is set.  const is used in the actual prototype to be compat‐
202       ible with other systems; however, this page doesn't show the qualifier,
203       to avoid confusing readers.
204

STANDARDS

206       getopt()
207              POSIX.1-2008.
208
209       getopt_long()
210       getopt_long_only()
211              GNU.
212
213              The use of '+' and '-' in optstring is a GNU extension.
214

HISTORY

216       getopt()
217              POSIX.1-2001, and POSIX.2.
218
219       On  some  older  implementations,  getopt()  was declared in <stdio.h>.
220       SUSv1 permitted the declaration  to  appear  in  either  <unistd.h>  or
221       <stdio.h>.   POSIX.1-1996  marked the use of <stdio.h> for this purpose
222       as LEGACY.  POSIX.1-2001 does not require the declaration to appear  in
223       <stdio.h>.
224

NOTES

226       A  program  that  scans  multiple argument vectors, or rescans the same
227       vector more than once, and wants to make use of GNU extensions such  as
228       '+'  and  '-' at the start of optstring, or changes the value of POSIX‐
229       LY_CORRECT between  scans,  must  reinitialize  getopt()  by  resetting
230       optind  to  0, rather than the traditional value of 1.  (Resetting to 0
231       forces the  invocation  of  an  internal  initialization  routine  that
232       rechecks POSIXLY_CORRECT and checks for GNU extensions in optstring.)
233
234       Command-line  arguments  are parsed in strict order meaning that an op‐
235       tion requiring an argument will consume the next  argument,  regardless
236       of  whether that argument is the correctly specified option argument or
237       simply the next option (in the scenario the user mis-specifies the com‐
238       mand  line).   For  example, if optstring is specified as "1n:" and the
239       user specifies the command line arguments  incorrectly  as  prog -n -1,
240       the  -n  option  will be given the optarg value "-1", and the -1 option
241       will be considered to have not been specified.
242

EXAMPLES

244   getopt()
245       The following trivial example program uses getopt() to handle two  pro‐
246       gram  options:  -n, with no associated value; and -t val, which expects
247       an associated value.
248
249       #include <stdio.h>
250       #include <stdlib.h>
251       #include <unistd.h>
252
253       int
254       main(int argc, char *argv[])
255       {
256           int flags, opt;
257           int nsecs, tfnd;
258
259           nsecs = 0;
260           tfnd = 0;
261           flags = 0;
262           while ((opt = getopt(argc, argv, "nt:")) != -1) {
263               switch (opt) {
264               case 'n':
265                   flags = 1;
266                   break;
267               case 't':
268                   nsecs = atoi(optarg);
269                   tfnd = 1;
270                   break;
271               default: /* '?' */
272                   fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
273                           argv[0]);
274                   exit(EXIT_FAILURE);
275               }
276           }
277
278           printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\n",
279                  flags, tfnd, nsecs, optind);
280
281           if (optind >= argc) {
282               fprintf(stderr, "Expected argument after options\n");
283               exit(EXIT_FAILURE);
284           }
285
286           printf("name argument = %s\n", argv[optind]);
287
288           /* Other code omitted */
289
290           exit(EXIT_SUCCESS);
291       }
292
293   getopt_long()
294       The following example program illustrates the use of getopt_long() with
295       most of its features.
296
297       #include <getopt.h>
298       #include <stdio.h>     /* for printf */
299       #include <stdlib.h>    /* for exit */
300
301       int
302       main(int argc, char *argv[])
303       {
304           int c;
305           int digit_optind = 0;
306
307           while (1) {
308               int this_option_optind = optind ? optind : 1;
309               int option_index = 0;
310               static struct option long_options[] = {
311                   {"add",     required_argument, 0,  0 },
312                   {"append",  no_argument,       0,  0 },
313                   {"delete",  required_argument, 0,  0 },
314                   {"verbose", no_argument,       0,  0 },
315                   {"create",  required_argument, 0, 'c'},
316                   {"file",    required_argument, 0,  0 },
317                   {0,         0,                 0,  0 }
318               };
319
320               c = getopt_long(argc, argv, "abc:d:012",
321                               long_options, &option_index);
322               if (c == -1)
323                   break;
324
325               switch (c) {
326               case 0:
327                   printf("option %s", long_options[option_index].name);
328                   if (optarg)
329                       printf(" with arg %s", optarg);
330                   printf("\n");
331                   break;
332
333               case '0':
334               case '1':
335               case '2':
336                   if (digit_optind != 0 && digit_optind != this_option_optind)
337                     printf("digits occur in two different argv-elements.\n");
338                   digit_optind = this_option_optind;
339                   printf("option %c\n", c);
340                   break;
341
342               case 'a':
343                   printf("option a\n");
344                   break;
345
346               case 'b':
347                   printf("option b\n");
348                   break;
349
350               case 'c':
351                   printf("option c with value '%s'\n", optarg);
352                   break;
353
354               case 'd':
355                   printf("option d with value '%s'\n", optarg);
356                   break;
357
358               case '?':
359                   break;
360
361               default:
362                   printf("?? getopt returned character code 0%o ??\n", c);
363               }
364           }
365
366           if (optind < argc) {
367               printf("non-option ARGV-elements: ");
368               while (optind < argc)
369                   printf("%s ", argv[optind++]);
370               printf("\n");
371           }
372
373           exit(EXIT_SUCCESS);
374       }
375

SEE ALSO

377       getopt(1), getsubopt(3)
378
379
380
381Linux man-pages 6.04              2023-04-03                         getopt(3)
Impressum