1GETOPT(3P)                 POSIX Programmer's Manual                GETOPT(3P)
2
3
4

PROLOG

6       This  manual  page is part of the POSIX Programmer's Manual.  The Linux
7       implementation of this interface may differ (consult the  corresponding
8       Linux  manual page for details of Linux behavior), or the interface may
9       not be implemented on Linux.
10

NAME

12       getopt, optarg, opterr, optind, optopt — command option parsing
13

SYNOPSIS

15       #include <unistd.h>
16
17       int getopt(int argc, char * const argv[], const char *optstring);
18       extern char *optarg;
19       extern int opterr, optind, optopt;
20

DESCRIPTION

22       The getopt() function is a command-line parser that shall follow  Util‐
23       ity  Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 in the Base Definitions
24       volume of POSIX.1‐2017, Section 12.2, Utility Syntax Guidelines.
25
26       The parameters argc and argv are the argument count and argument  array
27       as  passed  to main() (see exec()).  The argument optstring is a string
28       of recognized option characters;  if  a  character  is  followed  by  a
29       <colon>, the option takes an argument. All option characters allowed by
30       Utility Syntax Guideline 3 are allowed in optstring.   The  implementa‐
31       tion may accept other characters as an extension.
32
33       The variable optind is the index of the next element of the argv[] vec‐
34       tor to be processed. It shall be initialized to 1 by  the  system,  and
35       getopt()  shall update it when it finishes with each element of argv[].
36       If the application sets optind to zero  before  calling  getopt(),  the
37       behavior  is  unspecified.  When an element of argv[] contains multiple
38       option characters, it is  unspecified  how  getopt()  determines  which
39       options have already been processed.
40
41       The getopt() function shall return the next option character (if one is
42       found) from argv that matches a character in optstring, if there is one
43       that  matches.  If the option takes an argument, getopt() shall set the
44       variable optarg to point to the option-argument as follows:
45
46        1. If the option was the last character in the string pointed to by an
47           element  of  argv,  then  optarg  shall contain the next element of
48           argv, and optind shall be incremented by 2. If the resulting  value
49           of  optind  is  greater than argc, this indicates a missing option-
50           argument, and getopt() shall return an error indication.
51
52        2. Otherwise, optarg shall point to the string  following  the  option
53           character  in that element of argv, and optind shall be incremented
54           by 1.
55
56       If, when getopt() is called:
57
58
59            argv[optind]  is a null pointer
60           *argv[optind]  is not the character -
61            argv[optind]  points to the string "-"
62
63       getopt() shall return -1 without changing optind.  If:
64
65
66           argv[optind]   points to the string "--"
67
68       getopt() shall return -1 after incrementing optind.
69
70       If getopt() encounters an option character that  is  not  contained  in
71       optstring,  it shall return the <question-mark> ('?')  character. If it
72       detects a missing option-argument, it shall return the <colon>  charac‐
73       ter  (':')  if  the  first  character  of optstring was a <colon>, or a
74       <question-mark> character ('?')  otherwise. In  either  case,  getopt()
75       shall  set  the variable optopt to the option character that caused the
76       error. If the application has not set the variable opterr to 0 and  the
77       first  character  of  optstring  is  not a <colon>, getopt() shall also
78       print a diagnostic message to stderr in the format  specified  for  the
79       getopts  utility,  unless  the  stderr  stream has wide orientation, in
80       which case the behavior is undefined.
81
82       The getopt() function need not be thread-safe.
83

RETURN VALUE

85       The getopt() function shall return the next option character  specified
86       on the command line.
87
88       A  <colon>  (':') shall be returned if getopt() detects a missing argu‐
89       ment and the first character of optstring was a <colon> (':').
90
91       A <question-mark> ('?')  shall be returned if  getopt()  encounters  an
92       option character not in optstring or detects a missing argument and the
93       first character of optstring was not a <colon> (':').
94
95       Otherwise, getopt() shall return -1 when all command line  options  are
96       parsed.
97

ERRORS

99       If  the  application  has  not  set the variable opterr to 0, the first
100       character of optstring is not a <colon>, and a write error occurs while
101       getopt()  is  printing  a  diagnostic message to stderr, then the error
102       indicator for stderr shall be set; but getopt() shall still succeed and
103       the value of errno after getopt() is unspecified.
104
105       The following sections are informative.
106

EXAMPLES

108   Parsing Command Line Options
109       The  following  code fragment shows how you might process the arguments
110       for a utility that can take the mutually-exclusive options a and b  and
111       the options f and o, both of which require arguments:
112
113
114           #include <stdio.h>
115           #include <stdlib.h>
116           #include <unistd.h>
117
118           int
119           main(int argc, char *argv[ ])
120           {
121               int c;
122               int bflg = 0, aflg = 0, errflg = 0;
123               char *ifile;
124               char *ofile;
125               . . .
126               while ((c = getopt(argc, argv, ":abf:o:")) != -1) {
127                   switch(c) {
128                   case 'a':
129                       if (bflg)
130                           errflg++;
131                       else
132                           aflg++;
133                       break;
134                   case 'b':
135                       if (aflg)
136                           errflg++;
137                       else
138                           bflg++;
139                       break;
140                   case 'f':
141                       ifile = optarg;
142                       break;
143                   case 'o':
144                       ofile = optarg;
145                       break;
146                   case ':':       /* -f or -o without operand */
147                       fprintf(stderr,
148                           "Option -%c requires an operand\n", optopt);
149                       errflg++;
150                       break;
151                   case '?':
152                       fprintf(stderr,
153                           "Unrecognized option: '-%c'\n", optopt);
154                       errflg++;
155                   }
156               }
157               if (errflg) {
158                   fprintf(stderr, "usage: . . . ");
159                   exit(2);
160               }
161               for ( ; optind < argc; optind++) {
162                   if (access(argv[optind], R_OK)) {
163               . . .
164           }
165
166       This code accepts any of the following as equivalent:
167
168
169           cmd -ao arg path path
170           cmd -a -o arg path path
171           cmd -o arg -a path path
172           cmd -a -o arg -- path path
173           cmd -a -oarg path path
174           cmd -aoarg path path
175
176   Selecting Options from the Command Line
177       The  following  example  selects the type of database routines the user
178       wants to use based on the Options argument.
179
180
181           #include <unistd.h>
182           #include <string.h>
183           ...
184           const char *Options = "hdbtl";
185           ...
186           int dbtype, c;
187           char *st;
188           ...
189           dbtype = 0;
190           while ((c = getopt(argc, argv, Options)) != -1) {
191               if ((st = strchr(Options, c)) != NULL) {
192                   dbtype = st - Options;
193                   break;
194               }
195           }
196

APPLICATION USAGE

198       The getopt() function is only required  to  support  option  characters
199       included in Utility Syntax Guideline 3. Many historical implementations
200       of getopt() support other characters as options.  This  is  an  allowed
201       extension,  but applications that use extensions are not maximally por‐
202       table. Note that support for multi-byte option characters is only  pos‐
203       sible when such characters can be represented as type int.
204
205       Applications  which  use  wide-character  output  functions with stderr
206       should ensure that any calls to getopt() do not write to stderr, either
207       by  setting opterr to 0 or by ensuring the first character of optstring
208       is always a <colon>.
209
210       While ferror(stderr) may be used to detect failures to write a diagnos‐
211       tic to stderr when getopt() returns '?', the value of errno is unspeci‐
212       fied in such a condition. Applications desiring more control over  han‐
213       dling  write  failures should set opterr to 0 and independently perform
214       output to stderr, rather than relying on getopt() to do the output.
215

RATIONALE

217       The optopt variable  represents  historical  practice  and  allows  the
218       application to obtain the identity of the invalid option.
219
220       The  description  has been written to make it clear that getopt(), like
221       the getopts utility, deals with option-arguments whether separated from
222       the  option by <blank> characters or not. Note that the requirements on
223       getopt() and getopts are more stringent than the Utility Syntax  Guide‐
224       lines.
225
226       The  getopt()  function  shall  return  -1,  rather  than  EOF, so that
227       <stdio.h> is not required.
228
229       The special significance of a <colon> as the first  character  of  opt‐
230       string makes getopt() consistent with the getopts utility. It allows an
231       application to make a distinction between a  missing  argument  and  an
232       incorrect option letter without having to examine the option letter. It
233       is true that a missing argument can only be detected in one  case,  but
234       that is a case that has to be considered.
235

FUTURE DIRECTIONS

237       None.
238

SEE ALSO

240       exec
241
242       The Base Definitions volume of POSIX.1‐2017, Section 12.2, Utility Syn‐
243       tax Guidelines, <unistd.h>
244
245       The Shell and Utilities volume of POSIX.1‐2017, getopts
246
248       Portions of this text are reprinted and reproduced in  electronic  form
249       from  IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
250       table Operating System Interface (POSIX), The Open Group Base  Specifi‐
251       cations  Issue  7, 2018 Edition, Copyright (C) 2018 by the Institute of
252       Electrical and Electronics Engineers, Inc and The Open Group.   In  the
253       event of any discrepancy between this version and the original IEEE and
254       The Open Group Standard, the original IEEE and The Open Group  Standard
255       is  the  referee document. The original Standard can be obtained online
256       at http://www.opengroup.org/unix/online.html .
257
258       Any typographical or formatting errors that appear  in  this  page  are
259       most likely to have been introduced during the conversion of the source
260       files to man page format. To report such errors,  see  https://www.ker
261       nel.org/doc/man-pages/reporting_bugs.html .
262
263
264
265IEEE/The Open Group                  2017                           GETOPT(3P)
Impressum