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       If  getopt() does not recognize an option character, it prints an error
82       message to stderr, stores the character in  optopt,  and  returns  '?'.
83       The  calling program may prevent the error message by setting opterr to
84       0.
85
86       If getopt() finds an option character in argv that was not included  in
87       optstring,  or  if it detects a missing option argument, it returns '?'
88       and sets the external variable optopt to the actual  option  character.
89       If  the  first  character  (following any optional '+' or '-' described
90       above) of optstring is a colon (':'), then getopt() returns ':' instead
91       of  '?'  to  indicate  a  missing  option  argument.   If  an error was
92       detected, and the first character of optstring is not a colon, and  the
93       external  variable  opterr  is nonzero (which is the default), getopt()
94       prints an error message.
95
96   getopt_long() and getopt_long_only()
97       The getopt_long() function works like  getopt()  except  that  it  also
98       accepts long options, started with two dashes.  (If the program accepts
99       only long options, then optstring  should  be  specified  as  an  empty
100       string  (""),  not  NULL.)  Long option names may be abbreviated if the
101       abbreviation is unique or is an exact match for some defined option.  A
102       long  option  may  take  a  parameter, of the form --arg=param or --arg
103       param.
104
105       longopts is a pointer to the first element of an array of struct option
106       declared in <getopt.h> as
107
108           struct option {
109               const char *name;
110               int         has_arg;
111               int        *flag;
112               int         val;
113           };
114
115       The meanings of the different fields are:
116
117       name   is the name of the long option.
118
119       has_arg
120              is:  no_argument (or 0) if the option does not take an argument;
121              required_argument (or 1) if the option requires an argument;  or
122              optional_argument  (or  2) if the option takes an optional argu‐
123              ment.
124
125       flag   specifies how results are returned for a long option.   If  flag
126              is  NULL,  then  getopt_long()  returns  val.  (For example, the
127              calling program may set val to the equivalent short option char‐
128              acter.)   Otherwise, getopt_long() returns 0, and flag points to
129              a variable which is set to val if the option is found, but  left
130              unchanged if the option is not found.
131
132       val    is  the value to return, or to load into the variable pointed to
133              by flag.
134
135       The last element of the array has to be filled with zeros.
136
137       If longindex is not NULL, it points to a variable which is set  to  the
138       index of the long option relative to longopts.
139
140       getopt_long_only()  is  like getopt_long(), but '-' as well as "--" can
141       indicate a long option.  If an option that starts with '-'  (not  "--")
142       doesn't  match  a  long  option,  but  does match a short option, it is
143       parsed as a short option instead.
144

RETURN VALUE

146       If an option was successfully found, then getopt() returns  the  option
147       character.  If all command-line options have been parsed, then getopt()
148       returns -1.  If getopt() encounters an option character that was not in
149       optstring, then '?' is returned.  If getopt() encounters an option with
150       a missing argument, then the return value depends on the first  charac‐
151       ter  in optstring: if it is ':', then ':' is returned; otherwise '?' is
152       returned.
153
154       getopt_long() and getopt_long_only() also return the  option  character
155       when  a short option is recognized.  For a long option, they return val
156       if flag is NULL, and 0 otherwise.  Error and -1 returns are the same as
157       for  getopt(), plus '?' for an ambiguous match or an extraneous parame‐
158       ter.
159

ENVIRONMENT

161       POSIXLY_CORRECT
162              If this is set, then option processing stops as soon as a nonop‐
163              tion argument is encountered.
164
165       _<PID>_GNU_nonoption_argv_flags_
166              This  variable  was  used by bash(1) 2.0 to communicate to glibc
167              which arguments are the results of  wildcard  expansion  and  so
168              should  not be considered as options.  This behavior was removed
169              in bash(1) version 2.01, but the support remains in glibc.
170

CONFORMING TO

172       getopt():
173              POSIX.2 and  POSIX.1-2001,  provided  the  environment  variable
174              POSIXLY_CORRECT  is set.  Otherwise, the elements of argv aren't
175              really const, because we permute them.  We pretend they're const
176              in the prototype to be compatible with other systems.
177
178              The use of '+' and '-' in optstring is a GNU extension.
179
180              On   some   older  implementations,  getopt()  was  declared  in
181              <stdio.h>.  SUSv1 permitted the declaration to appear in  either
182              <unistd.h>   or  <stdio.h>.   POSIX.1-2001  marked  the  use  of
183              <stdio.h> for this purpose as  LEGACY.   POSIX.1-2001  does  not
184              allow the declaration to appear in <stdio.h>.
185
186       getopt_long() and getopt_long_only():
187              These functions are GNU extensions.
188

NOTES

190       A  program  that  scans  multiple argument vectors, or rescans the same
191       vector more than once, and wants to make use of GNU extensions such  as
192       '+'  and  '-'  at  the  start  of  optstring,  or  changes the value of
193       POSIXLY_CORRECT between scans, must reinitialize getopt() by  resetting
194       optind  to  0, rather than the traditional value of 1.  (Resetting to 0
195       forces the  invocation  of  an  internal  initialization  routine  that
196       rechecks POSIXLY_CORRECT and checks for GNU extensions in optstring.)
197

BUGS

199       The  POSIX.2  specification of getopt() has a technical error described
200       in POSIX.2 Interpretation 150.  The GNU  implementation  (and  probably
201       all  other implementations) implements the correct behavior rather than
202       that specified.
203

EXAMPLE

205       The following trivial example program uses getopt() to handle two  pro‐
206       gram  options:  -n, with no associated value; and -t val, which expects
207       an associated value.
208
209       #include <unistd.h>
210       #include <stdlib.h>
211       #include <stdio.h>
212
213       int
214       main(int argc, char *argv[])
215       {
216           int flags, opt;
217           int nsecs, tfnd;
218
219           nsecs = 0;
220           tfnd = 0;
221           flags = 0;
222           while ((opt = getopt(argc, argv, "nt:")) != -1) {
223               switch (opt) {
224               case 'n':
225                   flags = 1;
226                   break;
227               case 't':
228                   nsecs = atoi(optarg);
229                   tfnd = 1;
230                   break;
231               default: /* '?' */
232                   fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
233                           argv[0]);
234                   exit(EXIT_FAILURE);
235               }
236           }
237
238           printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
239
240           if (optind >= argc) {
241               fprintf(stderr, "Expected argument after options\n");
242               exit(EXIT_FAILURE);
243           }
244
245           printf("name argument = %s\n", argv[optind]);
246
247           /* Other code omitted */
248
249           exit(EXIT_SUCCESS);
250       }
251
252       The following example program illustrates the use of getopt_long() with
253       most of its features.
254
255       #include <stdio.h>     /* for printf */
256       #include <stdlib.h>    /* for exit */
257       #include <getopt.h>
258
259       int
260       main(int argc, char **argv)
261       {
262           int c;
263           int digit_optind = 0;
264
265           while (1) {
266               int this_option_optind = optind ? optind : 1;
267               int option_index = 0;
268               static struct option long_options[] = {
269                   {"add",     required_argument, 0,  0 },
270                   {"append",  no_argument,       0,  0 },
271                   {"delete",  required_argument, 0,  0 },
272                   {"verbose", no_argument,       0,  0 },
273                   {"create",  required_argument, 0, 'c'},
274                   {"file",    required_argument, 0,  0 },
275                   {0,         0,                 0,  0 }
276               };
277
278               c = getopt_long(argc, argv, "abc:d:012",
279                        long_options, &option_index);
280               if (c == -1)
281                   break;
282
283               switch (c) {
284               case 0:
285                   printf("option %s", long_options[option_index].name);
286                   if (optarg)
287                       printf(" with arg %s", optarg);
288                   printf("\n");
289                   break;
290
291               case '0':
292               case '1':
293               case '2':
294                   if (digit_optind != 0 && digit_optind != this_option_optind)
295                     printf("digits occur in two different argv-elements.\n");
296                   digit_optind = this_option_optind;
297                   printf("option %c\n", c);
298                   break;
299
300               case 'a':
301                   printf("option a\n");
302                   break;
303
304               case 'b':
305                   printf("option b\n");
306                   break;
307
308               case 'c':
309                   printf("option c with value '%s'\n", optarg);
310                   break;
311
312               case 'd':
313                   printf("option d with value '%s'\n", optarg);
314                   break;
315
316               case '?':
317                   break;
318
319               default:
320                   printf("?? getopt returned character code 0%o ??\n", c);
321               }
322           }
323
324           if (optind < argc) {
325               printf("non-option ARGV-elements: ");
326               while (optind < argc)
327                   printf("%s ", argv[optind++]);
328               printf("\n");
329           }
330
331           exit(EXIT_SUCCESS);
332       }
333

SEE ALSO

335       getsubopt(3)
336

COLOPHON

338       This  page  is  part of release 3.53 of the Linux man-pages project.  A
339       description of the project, and information about reporting  bugs,  can
340       be found at http://www.kernel.org/doc/man-pages/.
341
342
343
344GNU                               2010-11-01                         GETOPT(3)
Impressum