1GETOPT(3)                  Linux Programmer's Manual                 GETOPT(3)
2
3
4

NAME

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

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ENVIRONMENT

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

ATTRIBUTES

178       For  an  explanation  of  the  terms  used   in   this   section,   see
179       attributes(7).
180
181       ┌─────────────────────────┬───────────────┬───────────────────────────┐
182Interface                Attribute     Value                     
183       ├─────────────────────────┼───────────────┼───────────────────────────┤
184getopt(), getopt_long(), │ Thread safety │ MT-Unsafe race:getopt env │
185getopt_long_only()       │               │                           │
186       └─────────────────────────┴───────────────┴───────────────────────────┘

CONFORMING TO

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

NOTES

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

EXAMPLE

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 */
270       #include <stdlib.h>    /* for exit */
271       #include <getopt.h>
272
273       int
274       main(int argc, char **argv)
275       {
276           int c;
277           int digit_optind = 0;
278
279           while (1) {
280               int this_option_optind = optind ? optind : 1;
281               int option_index = 0;
282               static struct option long_options[] = {
283                   {"add",     required_argument, 0,  0 },
284                   {"append",  no_argument,       0,  0 },
285                   {"delete",  required_argument, 0,  0 },
286                   {"verbose", no_argument,       0,  0 },
287                   {"create",  required_argument, 0, 'c'},
288                   {"file",    required_argument, 0,  0 },
289                   {0,         0,                 0,  0 }
290               };
291
292               c = getopt_long(argc, argv, "abc:d:012",
293                        long_options, &option_index);
294               if (c == -1)
295                   break;
296
297               switch (c) {
298               case 0:
299                   printf("option %s", long_options[option_index].name);
300                   if (optarg)
301                       printf(" with arg %s", optarg);
302                   printf("\n");
303                   break;
304
305               case '0':
306               case '1':
307               case '2':
308                   if (digit_optind != 0 && digit_optind != this_option_optind)
309                     printf("digits occur in two different argv-elements.\n");
310                   digit_optind = this_option_optind;
311                   printf("option %c\n", c);
312                   break;
313
314               case 'a':
315                   printf("option a\n");
316                   break;
317
318               case 'b':
319                   printf("option b\n");
320                   break;
321
322               case 'c':
323                   printf("option c with value '%s'\n", optarg);
324                   break;
325
326               case 'd':
327                   printf("option d with value '%s'\n", optarg);
328                   break;
329
330               case '?':
331                   break;
332
333               default:
334                   printf("?? getopt returned character code 0%o ??\n", c);
335               }
336           }
337
338           if (optind < argc) {
339               printf("non-option ARGV-elements: ");
340               while (optind < argc)
341                   printf("%s ", argv[optind++]);
342               printf("\n");
343           }
344
345           exit(EXIT_SUCCESS);
346       }
347

SEE ALSO

349       getopt(1), getsubopt(3)
350

COLOPHON

352       This  page  is  part of release 5.02 of the Linux man-pages project.  A
353       description of the project, information about reporting bugs,  and  the
354       latest     version     of     this    page,    can    be    found    at
355       https://www.kernel.org/doc/man-pages/.
356
357
358
359GNU                               2019-03-06                         GETOPT(3)
Impressum