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