1getopt(3C) Standard C Library Functions getopt(3C)
2
3
4
6 getopt - command option parsing
7
9 SVID3, XPG3
10 #include <stdio.h>
11
12 int getopt(int argc, char * const argv[], const char *optstring);
13
14
15 extern char *optarg;
16
17
18 extern int optind, opterr, optopt;
19
20
21 POSIX.2, XPG4, SUS, SUSv2, SUSv3
22 #include <unistd.h>
23
24 int getopt(int argc, char * const argv[], const char *optstring);
25
26
27 extern char *optarg;
28
29
30 extern int optind, opterr, optopt;
31
32
34 The getopt() function is a command line parser that can be used by
35 applications that follow Basic Utility Syntax Guidelines 3, 4, 5, 6, 7,
36 9, and 10 which parallel those defined by application portability stan‐
37 dards (see intro(1)). It can also be used by applications which addi‐
38 tionally follow the Command Line Interface Paradigm (CLIP) syntax
39 extension guidelines 15, 16, and 17. It partially enforces guideline 18
40 by requiring that every option has a short-name, but it allows multiple
41 long-names to be associated with an option. The remaining guidelines
42 are not addressed by getopt() and are the responsibility of the appli‐
43 cation.
44
45
46 The argc and argv arguments are the argument count and argument array
47 as passed to main (see exec(2)). The optstring argument specifies the
48 acceptable options. For utilities wanting to conform to the Basic Util‐
49 ity Syntax Guidelines, optstring is a string of recognized option char‐
50 acters. All option characters allowed by Utility Syntax Guideline 3 are
51 allowed in optstring. If a character is followed by a colon (:), the
52 option is expected to have an option-argument, which can be separated
53 from it by white space. Utilities wanting to conform to the extended
54 CLIP guidelines can specify long-option equivalents to short options by
55 following the short-option character (and optional colon) with a
56 sequence of strings, each enclosed in parentheses, that specify the
57 long-option aliases.
58
59
60 The getopt() function returns the short-option character in optstring
61 that corresponds to the next option found in argv.
62
63
64 The getopt() function places in optind the argv index of the next argu‐
65 ment to be processed. The optind variable is external and is initial‐
66 ized to 1 before the first call to getopt(). The getopt() function sets
67 the variable optarg to point to the start of the option-argument as
68 follows:
69
70 o If the option is a short option and that character is the
71 last character in the argument, then optarg contains the
72 next element of argv, and optind is incremented by 2.
73
74 o If the option is a short option and that character is not
75 the last character in the argument, then optarg points to
76 the string following the option character in that argument,
77 and optind is incremented by 1.
78
79 o If the option is a long option and the character equals is
80 not found in the argument, then optarg contains the next
81 element of argv, and optind is incremented by 2.
82
83 o If the option is a long option and the character equals is
84 found in the argument, then optarg points to the string fol‐
85 lowing the equals character in that argument and optind is
86 incremented by 1.
87
88
89 In all cases, if the resulting value of optind is not less than argc,
90 this indicates a missing option-argument and getopt() returns an error
91 indication.
92
93
94 When all options have been processed (that is, up to the first oper‐
95 and), getopt() returns -1. The special option "--"(two hyphens) can be
96 used to delimit the end of the options; when it is encountered, -1 is
97 returned and "--" is skipped. This is useful in delimiting non-option
98 arguments that begin with "-" (hyphen).
99
100
101 If getopt() encounters a short-option character or a long-option string
102 not described in the opstring argument, it returns the question-mark
103 (?) character. If it detects a missing option-argument, it also returns
104 the question-mark (?) character, unless the first character of the opt‐
105 string argument was a colon (:), in which case getopt() returns the
106 colon (:) character. For short options, getopt() sets the variable
107 optopt to the option character that caused the error. For long options,
108 optopt is set to the hyphen (-) character and the failing long option
109 can be identified through argv[optind-1]. If the application has not
110 set the variable opterr to 0 and the first character of optstring is
111 not a colon (:), getopt() also prints a diagnostic message to stderr.
112
114 The getopt() function returns the short-option character associated
115 with the option recognized.
116
117
118 A colon (:) is returned if getopt() detects a missing argument and the
119 first character of optstring was a colon (:).
120
121
122 A question mark (?) is returned if getopt() encounters an option not
123 specified in optstring or detects a missing argument and the first
124 character of optstring was not a colon (:).
125
126
127 Otherwise, getopt() returns -1 when all command line options are
128 parsed.
129
131 No errors are defined.
132
134 Example 1 Parsing Command Line Options
135
136
137 The following code fragment shows how you might process the arguments
138 for a utility that can take the mutually-exclusive options a and b and
139 the options f and o, both of which require arguments:
140
141
142 #include <unistd.h>
143
144 int
145 main(int argc, char *argv[ ])
146 {
147 int c;
148 int bflg, aflg, errflg;
149 char *ifile;
150 char *ofile;
151 extern char *optarg;
152 extern int optind, optopt;
153 . . .
154 while ((c = getopt(argc, argv, ":abf:o:")) != -1) {
155 switch(c) {
156 case 'a':
157 if (bflg)
158 errflg++;
159 else
160 aflg++;
161 break;
162 case 'b':
163 if (aflg)
164 errflg++;
165 else {
166 bflg++;
167 bproc();
168 }
169 break;
170 case 'f':
171 ifile = optarg;
172 break;
173 case 'o':
174 ofile = optarg;
175 break;
176 case ':': /* -f or -o without operand */
177 fprintf(stderr,
178 "Option -%c requires an operand\n", optopt);
179 errflg++;
180 break;
181 case '?':
182 fprintf(stderr,
183 "Unrecognized option: -%c\n", optopt);
184 errflg++;
185 }
186 }
187 if (errflg) {
188 fprintf(stderr, "usage: . . . ");
189 exit(2);
190 }
191 for ( ; optind < argc; optind++) {
192 if (access(argv[optind], R_OK)) {
193 . . .
194 }
195
196
197
198 This code accepts any of the following as equivalent:
199
200
201 cmd -ao arg path path
202 cmd -a -o arg path path
203 cmd -o arg -a path path
204 cmd -a -o arg -- path path
205 cmd -a -oarg path path
206 cmd -aoarg path path
207
208
209 Example 2 Check Options and Arguments.
210
211
212 The following example parses a set of command line options and prints
213 messages to standard output for each option and argument that it
214 encounters.
215
216
217 #include <unistd.h>
218 #include <stdio.h>
219 ...
220 int c;
221 char *filename;
222 extern char *optarg;
223 extern int optind, optopt, opterr;
224 ...
225 while ((c = getopt(argc, argv, ":abf:")) != -1) {
226 switch(c) {
227 case 'a':
228 printf("a is set\n");
229 break;
230 case 'b':
231 printf("b is set\n");
232 break;
233 case 'f':
234 filename = optarg;
235 printf("filename is %s\n", filename);
236 break;
237 case ':':
238 printf("-%c without filename\n", optopt);
239 break;
240 case '?':
241 printf("unknown arg %c\n", optopt);
242 break;
243 }
244 }
245
246
247
248 This example can be expanded to be CLIP-compliant by substituting the
249 following string for the optstring argument:
250
251
252 :a(ascii)b(binary)f:(in-file)o:(out-file)V(version)?(help)
253
254
255
256 and by replacing the '?' case processing with:
257
258
259 case 'V':
260 fprintf(stdout, "cmd 1.1\n");
261 exit(0);
262 case '?':
263 if (optopt == '?') {
264 print_help();
265 exit(0);
266 }
267 if (optopt == '-')
268 fprintf(stderr,
269 "unrecognized option: %s\n", argv[optind-1]);
270 else
271 fprintf(stderr,
272 "unrecognized option: -%c\n", optopt);
273 errflg++;
274 break;
275
276
277
278 and by replacing the ':' case processing with:
279
280
281 case ':': /* -f or -o without operand */
282 if (optopt == '-')
283 fprintf(stderr,
284 "Option %s requires an operand\n", argv[optind-1]);
285 else
286 fprintf(stderr,
287 "Option -%c requires an operand\n", optopt);
288 errflg++;
289 break;
290
291
292
293 While not encouraged by the CLIP specification, multiple long-option
294 aliases can also be assigned as shown in the following example:
295
296
297 :a(ascii)b(binary):(in-file)(input)o:(outfile)(output)V(version)?(help)
298
299
301 See environ(5) for descriptions of the following environment variables
302 that affect the execution of getopt(): LANG, LC_ALL, and LC_MESSAGES.
303
304 LC_CTYPE Determine the locale for the interpretation of sequences of
305 bytes as characters in optstring.
306
307
309 The getopt() function does not fully check for mandatory arguments
310 because there is no unambiguous algorithm to do so. Given an option
311 string a:b and the input -a -b, getopt() assumes that -b is the manda‐
312 tory argument to the -a option and not that -a is missing a mandatory
313 argument. Indeed, the only time a missing option-argument can be reli‐
314 ably detected is when the option is the final option on the command
315 line and is not followed by any command arguments.
316
317
318 It is a violation of the Basic Utility Command syntax standard (see
319 Intro(1)) for options with arguments to be grouped with other options,
320 as in cmd -abo filename , where a and b are options, o is an option
321 that requires an argument, and filename is the argument to o. Although
322 this syntax is permitted in the current implementation, it should not
323 be used because it may not be supported in future releases. The cor‐
324 rect syntax to use is:
325
326 cmd −ab −o filename
327
328
329
331 See attributes(5) for descriptions of the following attributes:
332
333
334
335
336 ┌─────────────────────────────┬─────────────────────────────┐
337 │ ATTRIBUTE TYPE │ ATTRIBUTE VALUE │
338 ├─────────────────────────────┼─────────────────────────────┤
339 │Interface Stability │Committed │
340 ├─────────────────────────────┼─────────────────────────────┤
341 │MT-Level │Unsafe │
342 ├─────────────────────────────┼─────────────────────────────┤
343 │Standard │See below. │
344 └─────────────────────────────┴─────────────────────────────┘
345
346
347 For the Basic Utility Command syntax is Standard, see standards(5).
348
350 Intro(1), getopt(1), getopts(1), getsubopt(3C), gettext(3C), setlo‐
351 cale(3C), attributes(5), environ(5), standards(5)
352
353
354
355SunOS 5.11 16 Oct 2007 getopt(3C)