xref: /openbsd/lib/libc/stdlib/getopt.3 (revision a6445c1d)
1.\" Copyright (c) 1988, 1991, 1993
2.\"	The Regents of the University of California.  All rights reserved.
3.\"
4.\" Redistribution and use in source and binary forms, with or without
5.\" modification, are permitted provided that the following conditions
6.\" are met:
7.\" 1. Redistributions of source code must retain the above copyright
8.\"    notice, this list of conditions and the following disclaimer.
9.\" 2. Redistributions in binary form must reproduce the above copyright
10.\"    notice, this list of conditions and the following disclaimer in the
11.\"    documentation and/or other materials provided with the distribution.
12.\" 3. Neither the name of the University nor the names of its contributors
13.\"    may be used to endorse or promote products derived from this software
14.\"    without specific prior written permission.
15.\"
16.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
17.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
20.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26.\" SUCH DAMAGE.
27.\"
28.\"	$OpenBSD: getopt.3,v 1.44 2014/01/21 03:15:45 schwarze Exp $
29.\"
30.Dd $Mdocdate: January 21 2014 $
31.Dt GETOPT 3
32.Os
33.Sh NAME
34.Nm getopt
35.Nd get option character from command line argument list
36.Sh SYNOPSIS
37.In unistd.h
38.Vt extern char *optarg;
39.Vt extern int   opterr;
40.Vt extern int   optind;
41.Vt extern int   optopt;
42.Vt extern int   optreset;
43.Ft int
44.Fn getopt "int argc" "char * const *argv" "const char *optstring"
45.Sh DESCRIPTION
46The
47.Fn getopt
48function incrementally parses a command line argument list
49.Fa argv
50and returns the next
51.Em known
52option character.
53An option character is
54.Em known
55if it has been specified in the string of accepted option characters,
56.Fa optstring .
57.Pp
58The option string
59.Fa optstring
60may contain the following elements: individual characters,
61characters followed by a colon, and characters followed by two colons.
62A character followed by a single colon indicates that an argument
63is to follow the option on the command line.
64Two colons indicates that the argument is optional \- this is an
65extension not covered by POSIX.
66For example, an option string
67.Qq x
68recognizes an option
69.Fl x ,
70and an option string
71.Qq Li x:
72recognizes an option and argument
73.Fl x Ar argument .
74It does not matter to
75.Fn getopt
76if a following argument has leading whitespace; except in the case where
77the argument is optional, denoted with two colons, no leading whitespace
78is permitted.
79.Pp
80On return from
81.Fn getopt ,
82.Va optarg
83points to an option argument, if it is anticipated,
84and the variable
85.Va optind
86contains the index to the next
87.Fa argv
88argument for a subsequent call
89to
90.Fn getopt .
91.Pp
92The variables
93.Va opterr
94and
95.Va optind
96are both initialized to 1.
97The
98.Va optind
99variable may be set to another value larger than 0 before a set of calls to
100.Fn getopt
101in order to skip over more or less
102.Fa argv
103entries.
104An
105.Va optind
106value of 0 is reserved for compatibility with GNU
107.Fn getopt .
108.Pp
109In order to use
110.Fn getopt
111to evaluate multiple sets of arguments, or to evaluate a single set of
112arguments multiple times,
113the variable
114.Va optreset
115must be set to 1 before the second and each additional set of calls to
116.Fn getopt ,
117and the variable
118.Va optind
119must be reinitialized.
120.Pp
121The
122.Fn getopt
123function returns \-1 when the argument list is exhausted.
124The interpretation of options in the argument list may be cancelled
125by the option
126.Ql --
127(double dash) which causes
128.Fn getopt
129to signal the end of argument processing and return \-1.
130When all options have been processed (i.e., up to the first non-option
131argument),
132.Fn getopt
133returns \-1.
134.Sh RETURN VALUES
135The
136.Fn getopt
137function returns the next known option character in
138.Fa optstring .
139If
140.Fn getopt
141encounters a character not found in
142.Fa optstring
143or if it detects a missing option argument,
144it returns
145.Sq \&?
146(question mark).
147If
148.Fa optstring
149has a leading
150.Sq \&:
151then a missing option argument causes
152.Sq \&:
153to be returned instead of
154.Sq \&? .
155In either case, the variable
156.Va optopt
157is set to the character that caused the error.
158The
159.Fn getopt
160function returns \-1 when the argument list is exhausted.
161.Sh EXAMPLES
162The following code accepts the options
163.Fl b
164and
165.Fl f Ar argument
166and adjusts
167.Va argc
168and
169.Va argv
170after option argument processing has completed.
171.Bd -literal -offset indent
172int bflag, ch, fd;
173
174bflag = 0;
175while ((ch = getopt(argc, argv, "bf:")) != -1) {
176	switch (ch) {
177	case 'b':
178		bflag = 1;
179		break;
180	case 'f':
181		if ((fd = open(optarg, O_RDONLY, 0)) == -1)
182			err(1, "%s", optarg);
183		break;
184	default:
185		usage();
186		/* NOTREACHED */
187	}
188}
189argc -= optind;
190argv += optind;
191.Ed
192.Sh DIAGNOSTICS
193If the
194.Fn getopt
195function encounters a character not found in the string
196.Fa optstring
197or detects
198a missing option argument, it writes an error message to
199.Em stderr
200and returns
201.Ql \&? .
202Setting
203.Va opterr
204to a zero will disable these error messages.
205If
206.Fa optstring
207has a leading
208.Ql \&:
209then a missing option argument causes a
210.Ql \&:
211to be returned in addition to suppressing any error messages.
212.Pp
213Option arguments are allowed to begin with
214.Ql - ;
215this is reasonable but reduces the amount of error checking possible.
216.Sh SEE ALSO
217.Xr getopt 1 ,
218.Xr getopt_long 3 ,
219.Xr getsubopt 3
220.Sh STANDARDS
221The
222.Fn getopt
223function implements a superset of the functionality specified by
224.St -p1003.1 .
225.Pp
226The following extensions are supported:
227.Bl -tag -width "xxx"
228.It Li o
229The
230.Va optreset
231variable was added to make it possible to call the
232.Fn getopt
233function multiple times.
234.It Li o
235If the
236.Va optind
237variable is set to 0,
238.Fn getopt
239will behave as if the
240.Va optreset
241variable has been set.
242This is for compatibility with
243.Tn GNU
244.Fn getopt .
245New code should use
246.Va optreset
247instead.
248.It Li o
249If the first character of
250.Fa optstring
251is a plus sign
252.Pq Ql + ,
253it will be ignored.
254This is for compatibility with
255.Tn GNU
256.Fn getopt .
257.It Li o
258If the first character of
259.Fa optstring
260is a dash
261.Pq Ql - ,
262non-options will be returned as arguments to the option character
263.Ql \e1 .
264This is for compatibility with
265.Tn GNU
266.Fn getopt .
267.It Li o
268A single dash
269.Pq Ql -
270may be specified as a character in
271.Fa optstring ,
272however it should
273.Em never
274have an argument associated with it.
275This allows
276.Fn getopt
277to be used with programs that expect
278.Ql -
279as an option flag.
280This practice is wrong, and should not be used in any current development.
281It is provided for backward compatibility
282.Em only .
283Care should be taken not to use
284.Ql -
285as the first character in
286.Fa optstring
287to avoid a semantic conflict with
288.Tn GNU
289.Fn getopt
290semantics (see above).
291By default, a single dash causes
292.Fn getopt
293to return \-1.
294.El
295.Pp
296Historic
297.Bx
298versions of
299.Fn getopt
300set
301.Fa optopt
302to the last option character processed.
303However, this conflicts with
304.St -p1003.1
305which stipulates that
306.Fa optopt
307be set to the last character that caused an error.
308.Sh HISTORY
309The
310.Fn getopt
311function appeared in
312.Bx 4.3 .
313.Sh BUGS
314The
315.Fn getopt
316function was once specified to return
317.Dv EOF
318instead of \-1.
319This was changed by
320.St -p1003.2-92
321to decouple
322.Fn getopt
323from
324.In stdio.h .
325.Pp
326It is possible to handle digits as option letters.
327This allows
328.Fn getopt
329to be used with programs that expect a number
330.Pq Dq Li \-3
331as an option.
332This practice is wrong, and should not be used in any current development.
333It is provided for backward compatibility
334.Em only .
335The following code fragment works in most cases and can handle mixed
336number and letter arguments.
337.Bd -literal -offset indent
338int aflag = 0, bflag = 0, ch, lastch = '\e0';
339int length = -1, newarg = 1, prevoptind = 1;
340
341while ((ch = getopt(argc, argv, "0123456789ab")) != -1) {
342	switch (ch) {
343	case '0': case '1': case '2': case '3': case '4':
344	case '5': case '6': case '7': case '8': case '9':
345		if (newarg || !isdigit(lastch))
346			length = 0;
347		else if (length > INT_MAX / 10)
348			usage();
349		length = (length * 10) + (ch - '0');
350		break;
351	case 'a':
352		aflag = 1;
353		break;
354	case 'b':
355		bflag = 1;
356		break;
357	default:
358		usage();
359	}
360	lastch = ch;
361	newarg = optind != prevoptind;
362	prevoptind = optind;
363}
364.Ed
365