xref: /openbsd/lib/libc/stdlib/getopt.3 (revision 404b540a)
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.41 2009/04/12 23:13:36 okan Exp $
29.\"
30.Dd $Mdocdate: April 12 2009 $
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.Fd #include <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 ENVIRONMENT
162.Bl -tag -width POSIXLY_CORRECTXX
163.It Ev POSIXLY_CORRECT
164If set, a leading
165.Sq -
166in
167.Ar optstring
168is ignored.
169.El
170.Sh EXAMPLES
171The following code accepts the options
172.Fl b
173and
174.Fl f Ar argument
175and adjusts
176.Va argc
177and
178.Va argv
179after option argument processing has completed.
180.Bd -literal -offset indent
181int bflag, ch, fd;
182
183bflag = 0;
184while ((ch = getopt(argc, argv, "bf:")) != -1) {
185	switch (ch) {
186	case 'b':
187		bflag = 1;
188		break;
189	case 'f':
190		if ((fd = open(optarg, O_RDONLY, 0)) == -1)
191			err(1, "%s", optarg);
192		break;
193	default:
194		usage();
195		/* NOTREACHED */
196	}
197}
198argc -= optind;
199argv += optind;
200.Ed
201.Sh DIAGNOSTICS
202If the
203.Fn getopt
204function encounters a character not found in the string
205.Fa optstring
206or detects
207a missing option argument, it writes an error message to
208.Em stderr
209and returns
210.Ql \&? .
211Setting
212.Va opterr
213to a zero will disable these error messages.
214If
215.Fa optstring
216has a leading
217.Ql \&:
218then a missing option argument causes a
219.Ql \&:
220to be returned in addition to suppressing any error messages.
221.Pp
222Option arguments are allowed to begin with
223.Ql - ;
224this is reasonable but reduces the amount of error checking possible.
225.Sh SEE ALSO
226.Xr getopt 1 ,
227.Xr getopt_long 3 ,
228.Xr getsubopt 3
229.Sh STANDARDS
230The
231.Fn getopt
232function implements a superset of the functionality specified by
233.St -p1003.1 .
234.Pp
235The following extensions are supported:
236.Bl -tag -width "xxx"
237.It Li o
238The
239.Va optreset
240variable was added to make it possible to call the
241.Fn getopt
242function multiple times.
243.It Li o
244If the
245.Va optind
246variable is set to 0,
247.Fn getopt
248will behave as if the
249.Va optreset
250variable has been set.
251This is for compatibility with
252.Tn GNU
253.Fn getopt .
254New code should use
255.Va optreset
256instead.
257.It Li o
258If the first character of
259.Fa optstring
260is a plus sign
261.Pq Ql + ,
262it will be ignored.
263This is for compatibility with
264.Tn GNU
265.Fn getopt .
266.It Li o
267If the first character of
268.Fa optstring
269is a dash
270.Pq Ql - ,
271non-options will be returned as arguments to the option character
272.Ql \e1 .
273This is for compatibility with
274.Tn GNU
275.Fn getopt .
276.It Li o
277A single dash
278.Pq Ql -
279may be specified as a character in
280.Fa optstring ,
281however it should
282.Em never
283have an argument associated with it.
284This allows
285.Fn getopt
286to be used with programs that expect
287.Ql -
288as an option flag.
289This practice is wrong, and should not be used in any current development.
290It is provided for backward compatibility
291.Em only .
292Care should be taken not to use
293.Ql -
294as the first character in
295.Fa optstring
296to avoid a semantic conflict with
297.Tn GNU
298.Fn getopt
299semantics (see above).
300By default, a single dash causes
301.Fn getopt
302to return \-1.
303.El
304.Pp
305Historic
306.Bx
307versions of
308.Fn getopt
309set
310.Fa optopt
311to the last option character processed.
312However, this conflicts with
313.St -p1003.1
314which stipulates that
315.Fa optopt
316be set to the last character that caused an error.
317.Sh HISTORY
318The
319.Fn getopt
320function appeared in
321.Bx 4.3 .
322.Sh BUGS
323The
324.Fn getopt
325function was once specified to return
326.Dv EOF
327instead of \-1.
328This was changed by
329.St -p1003.2-92
330to decouple
331.Fn getopt
332from
333.Aq Pa stdio.h .
334.Pp
335It is possible to handle digits as option letters.
336This allows
337.Fn getopt
338to be used with programs that expect a number
339.Pq Dq Li \-3
340as an option.
341This practice is wrong, and should not be used in any current development.
342It is provided for backward compatibility
343.Em only .
344The following code fragment works in most cases and can handle mixed
345number and letter arguments.
346.Bd -literal -offset indent
347int aflag = 0, bflag = 0, ch, lastch = '\e0';
348int length = -1, newarg = 1, prevoptind = 1;
349
350while ((ch = getopt(argc, argv, "0123456789ab")) != -1) {
351	switch (ch) {
352	case '0': case '1': case '2': case '3': case '4':
353	case '5': case '6': case '7': case '8': case '9':
354		if (newarg || !isdigit(lastch))
355			length = 0;
356		else if (length > INT_MAX / 10)
357			usage();
358		length = (length * 10) + (ch - '0');
359		break;
360	case 'a':
361		aflag = 1;
362		break;
363	case 'b':
364		bflag = 1;
365		break;
366	default:
367		usage();
368	}
369	lastch = ch;
370	newarg = optind != prevoptind;
371	prevoptind = optind;
372}
373.Ed
374