xref: /illumos-gate/usr/src/man/man3c/getopt_long.3c (revision dd72704bd9e794056c558153663c739e2012d721)
1.\"
2.\" Copyright (c) 1988, 1991, 1993
3.\"	The Regents of the University of California.  All rights reserved.
4.\"
5.\" Redistribution and use in source and binary forms, with or without
6.\" modification, are permitted provided that the following conditions
7.\" are met:
8.\" 1. Redistributions of source code must retain the above copyright
9.\"    notice, this list of conditions and the following disclaimer.
10.\" 2. Redistributions in binary form must reproduce the above copyright
11.\"    notice, this list of conditions and the following disclaimer in the
12.\"    documentation and/or other materials provided with the distribution.
13.\" 3. Neither the name of the University nor the names of its contributors
14.\"    may be used to endorse or promote products derived from this software
15.\"    without specific prior written permission.
16.\"
17.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27.\" SUCH DAMAGE.
28.\"
29.\"
30.\" Copyright 2018 Jason King
31.\" Copyright 2018, Joyent, Inc.
32.\" Copyright 2020 Oxide Computer Company
33.\"
34.Dd August 10, 2020
35.Dt GETOPT_LONG 3C
36.Os
37.Sh NAME
38.Nm getopt_long ,
39.Nm getopt_long_clip ,
40.Nm getopt_long_only
41.Nd get long options from command line argument list
42.Sh SYNOPSIS
43.In getopt.h
44.Vt extern char *optarg ;
45.Vt extern int optind ;
46.Vt extern int optopt ;
47.Vt extern int opterr ;
48.Ft int
49.Fo getopt_long
50.Fa "int argc"
51.Fa "char * const *argv"
52.Fa "const char *optstring"
53.Fa "const struct option *longopts"
54.Fa "int *longindex"
55.Fc
56.Ft int
57.Fo getopt_long_only
58.Fa "int argc"
59.Fa "char * const *argv"
60.Fa "const char *optstring"
61.Fa "const struct option *longopts"
62.Fa "int *longindex"
63.Fc
64.Ft int
65.Fo getopt_long_clip
66.Fa "int argc"
67.Fa "char * const *argv"
68.Fa "const char *optstring"
69.Fa "const struct option *longopts"
70.Fa "int *longindex"
71.Fc
72.Sh DESCRIPTION
73The
74.Fn getopt_long
75function is similar to
76.Xr getopt 3C
77but it accepts options in two forms: short options and long options.
78Short options are the traditional option flags that use a hyphen followed
79by a single character.
80This is the only form of option that is portable and it is supported by
81.Xr getopt 3C .
82Note, some implementation of
83.Xr getopt 3C
84do support non-standard extensions for long options; however, these are
85not portable and not considered in this manual page.
86Common example of short options are:
87.Fl a ,
88.Fl l ,
89and
90.Fl r .
91Long options use two hyphen characters are generally full words.
92The long versions of the above might be:
93.Fl -all ,
94.Fl -list ,
95and
96.Fl -recursive .
97.Pp
98The
99.Fn getopt_long
100function can be used to:
101.Bl -enum
102.It
103Support an option with both short and long forms.
104.It
105Support an option with only a short form.
106.It
107Support an option with only a long form.
108.El
109.Pp
110To have a short option selected, as with
111.Xr getopt 3C ,
112it must be listed in
113.Fa optstring .
114Long options are instead listed in the
115.Fa longopts
116array.
117For an option to have both a short and long form it must be present in
118both
119.Fa optstring
120and
121.Fa longopts .
122.Pp
123Long options can be handled in two different ways.
124In the first way, every long option understood by the program has a
125corresponding short option, and the option structure is only used to
126translate from long options to short options.
127When used in this fashion,
128.Fn getopt_long
129behaves identically to
130.Xr getopt 3C .
131This is a good way to add long option processing to an existing program
132with the minimum of rewriting.
133.Pp
134In the second mechanism, a long option sets a flag in the
135.Vt option
136structure passed, or will store a pointer to the command line argument
137in the
138.Vt option
139structure passed to it for options that take arguments.
140Additionally,
141the long option's argument may be specified as a single argument with
142an equal sign, e.g.,
143.Pp
144.Dl "myprogram --myoption=somevalue"
145.Pp
146When a long option is processed, the call to
147.Fn getopt_long
148will return 0.
149For this reason, long option processing without
150shortcuts is not backwards compatible with
151.Xr getopt 3C .
152.Pp
153It is possible to combine these methods, providing for long options
154processing with short option equivalents for some options.
155Less
156frequently used options would be processed as long options only.
157.Pp
158In
159.Fn getopt_long
160and
161.Fn getopt_long_only ,
162.Fa optstring
163acts similar to
164.Fa optstring
165in
166.Xr getopt 3C ,
167listing the set of supported short option flags.
168In addition,
169.Fa optstring
170can begin with
171.Ql +
172or
173.Ql - .
174If
175.Fa optstring
176begins with
177.Ql + ,
178the first non-option terminates option processing.
179This is equivalent to setting the environment variable
180.Ev POSIXLY_CORRECT .
181If
182.Fa optstring
183begins with
184.Ql - ,
185non-options are treated as options to the argument
186.Ql \e1 .
187.Pp
188If
189.Fa optstring
190does not begin with
191.Ql +
192and
193.Ev POSIXLY_CORRECT
194is not set, if
195.Ql W\&;
196appears in
197.Fa optstring ,
198.Ql "-W myoption"
199is treated the same as
200.Ql "--myoption"
201and
202.Va optarg
203is set to
204.Ql myoption .
205.Pp
206In
207.Fn getopt_long_clip ,
208.Ql +
209and
210.Ql -
211are ignored at the beginning of a string.
212.Pp
213The
214.Fn getopt_long ,
215.Fn getopt_long_only ,
216and
217.Fn getopt_long_clip
218functions require a structure to be initialized describing the long
219options.
220The structure is:
221.Bd -literal -offset indent
222struct option {
223	char *name;
224	int has_arg;
225	int *flag;
226	int val;
227};
228.Ed
229.Pp
230The
231.Fa name
232field should contain the option name without the leading double hyphen.
233.Pp
234The
235.Fa has_arg
236field should be one of:
237.Pp
238.Bl -tag -width ".Dv optional_argument" -offset indent -compact
239.It Dv no_argument
240no argument to the option is expected
241.It Dv required_argument
242an argument to the option is required
243.It Dv optional_argument
244an argument to the option may be presented
245.El
246.Pp
247If
248.Fa flag
249is not
250.Dv NULL ,
251then the integer pointed to by it will be set to the
252value in the
253.Fa val
254field and
255.Va optopt
256will be set to
257.Sy 0 .
258If the
259.Fa flag
260field is
261.Dv NULL ,
262then the
263.Fa val
264field will be returned and
265.Va optopt
266is set to the value in the
267.Fa val
268field.
269Setting
270.Fa flag
271to
272.Dv NULL
273and setting
274.Fa val
275to the corresponding short option will make this function act just
276like
277.Xr getopt 3C .
278.Pp
279If the
280.Fa longindex
281field is not
282.Dv NULL ,
283then the integer pointed to by it will be set to the index of the long
284option relative to
285.Fa longopts .
286.Pp
287The last element of the
288.Fa longopts
289array has to be filled with zeroes.
290.Pp
291The
292.Fn getopt_long_only
293function behaves identically to
294.Fn getopt_long
295with the exception that long options may start with
296.Ql -
297in addition to
298.Ql -- .
299If an option starting with
300.Ql -
301does not match a long option but does match a single-character option,
302the single-character option is returned.
303.Pp
304The
305.Fn getopt_long_clip
306function is a variation of
307.Fn getopt_long
308except that options must also adhere to the Sun CLIP specification.
309Specifically, the major differences from
310.Fn getopt_long
311are:
312.Bl -bullet -offset indent
313.It
314All option arguments are required
315.Po
316.Dv optional_argument
317is treated the same as
318.Dv required_argument
319.Pc .
320.It
321Long options cannot be abbreviated on the command line.
322.It
323Long options must use a double hyphen
324.Pq Ql -- .
325.It
326Option processing stops at the first non-option.
327.It
328All long options must have an equivalent short option (single character) and
329vice-versa.
330.It
331A leading
332.Ql +
333or
334.Ql -
335in
336.Fa optstring
337is ignored.
338.Fa optstring
339is treated as if it began after the leading
340.Ql +
341or
342.Ql - .
343.El
344.Pp
345On each call to
346.Fn getopt_long ,
347.Fn getopt_long_only ,
348or
349.Fn getopt_long ,
350.Va optind
351is set to the
352.Va argv
353index of the
354.Em next
355argument to be processed.
356.Va optind
357is initialized to
358.Sy 1
359prior to the first invocation of
360.Fn getopt_long ,
361.Fn getopt_long_only ,
362or
363.Fn getopt_long_clip .
364.Pp
365If
366.Va opterr
367is set to a non-zero value and
368.Fa optstring
369does not start with
370.Ql \&: ,
371.Fn getopt_long ,
372.Fn getopt_long_only ,
373and
374.Fn getopt_long_clip
375will print an error message to
376.Sy stderr
377when an error or invalid option is encountered.
378.Sh RETURN VALUES
379If the
380.Fa flag
381field in
382.Vt "struct option"
383is
384.Dv NULL ,
385.Fn getopt_long
386and
387.Fn getopt_long_only
388return the value specified in the
389.Fa val
390field, which is usually just the corresponding short option.
391If
392.Fa flag
393is not
394.Dv NULL ,
395these functions return 0 and store
396.Fa val
397in the location pointed to by
398.Fa flag .
399These functions return
400.Ql \&:
401if there was a missing option argument,
402.Ql \&?
403if the user specified an unknown or ambiguous option, and
404\-1 when the argument list has been exhausted.
405.Pp
406If a long option to
407.Fn getopt_long_clip
408is missing its equivalent short option (or vice-versa),\-1 is returned on the
409first call to
410.Fn getopt_long_clip ,
411and
412.Dv errno
413is set to
414.Er EINVAL .
415If
416.Va opterr
417is set to a non-zero value and
418.Fa optstring
419does not start with
420.Ql \&: ,
421an error message will be written to
422.Sy stderr .
423.Pp
424If
425.Fa optstring
426does not start with
427.Ql \&:
428and
429.Fn getopt_long ,
430.Fn getopt_long_only ,
431or
432.Fn getopt_long_clip
433return
434.Ql \&:
435or
436.Ql \&? ,
437if
438.Va opterr
439is set to a non-zero value, an error message is written to
440.Dv stderr .
441.Sh ENVIRONMENT
442The following environment variables can effect the execution of
443.Nm getopt_long ,
444.Nm getopt_long_only ,
445and
446.Nm getopt_long_clip :
447.Ev LANG ,
448.Ev LC_ALL ,
449.Ev LC_MESSAGES .
450See
451.Xr environ 7 .
452.Bl -tag -width ".Ev POSIXLY_CORRECT"
453.It Ev POSIXLY_CORRECT
454If set, option processing stops when the first non-option is found and
455a leading
456.Ql -
457or
458.Ql +
459in the
460.Fa optstring
461is ignored.
462.El
463.Sh USAGE
464Similar to
465.Xr getopt 3C ,
466since there is no unambiguous way to detect a missing option-argument except when the
467option is the last option on the command line, the
468.Fn getopt_long ,
469.Fn getopt_long_only ,
470and
471.Fn getopt_long_clip
472functions cannot fully check for mandatory arguments.
473For example, the option string
474.Ql ho\&:
475with an input of
476.Ql Fl o Fl h
477will assume that
478.Ql Fl h
479is the required argument to
480.Fl o
481instead of assuming that
482.Fl o
483is missing its option-argument.
484.Pp
485Like
486.Xr getopt 3C ,
487grouping options taking or requiring arguments with other options is a violation of the
488Basic Utility Command syntax standard (see
489.Xr Intro 1 ) .
490For example, given the option string
491.Ql cde\&: ,
492running:
493.Pp
494.Dl cmd Fl cde Ar ieio
495.Pp
496is incorrect.
497Current versions of
498.Nm getopt_long ,
499.Nm getopt_long_only ,
500and
501.Nm getopt_long_clip
502accept this, however future versions may not support this.
503The correct invocation would be:
504.Pp
505.Dl cmd Fl cd Fl e Ar ieio
506.Sh EXAMPLES
507.Sy Example 1
508Basic usage of
509.Fn getopt_long .
510.Pp
511In this example, the short options,
512.Fl b
513and
514.Fl f
515are treated the same way as their corresponding long options
516.Fl -buffy
517and
518.Fl -fluoride .
519The long option
520.Fl -daggerset
521is only matched as a long option.
522.Pp
523.Bd -literal -compact
524int bflag, ch, fd;
525int daggerset;
526
527/* options descriptor */
528static struct option longopts[] = {
529	{ "buffy",	no_argument,		NULL,		'b' },
530	{ "fluoride",	required_argument,	NULL,		'f' },
531	{ "daggerset",	no_argument,		\*[Am]daggerset,	1 },
532	{ NULL,		0,			NULL,		0 }
533};
534
535bflag = 0;
536while ((ch = getopt_long(argc, argv, "bf:", longopts, NULL)) != -1) {
537	switch (ch) {
538	case 'b':
539		bflag = 1;
540		break;
541	case 'f':
542		if ((fd = open(optarg, O_RDONLY, 0)) == -1)
543			err(1, "unable to open %s", optarg);
544		break;
545	case 0:
546		if (daggerset) {
547			fprintf(stderr,"Buffy will use her dagger to "
548			    "apply fluoride to dracula's teeth\en");
549		}
550		break;
551	default:
552		usage();
553	}
554}
555argc -= optind;
556argv += optind;
557.Ed
558.Pp
559.Sy Example 2
560Mixing short-only and long-only options.
561.Pp
562This example has a program that uses both short and long options and
563always causes the option to be handled in a way that is similar to
564.Xr getopt 3C
565regardless of if it is short or long.
566Options that are only long options are assigned a character value that
567is outside of the common 8-bit range
568.Po
569starting at
570.Dv USHRT_MAX
571+ 1.
572.Pc
573This allows them to still integrate into a normal
574.Xr getopt 3C
575style option processing loop.
576.Pp
577In the following code,
578.Fl s
579is only usable as a short option while
580.Fl -long-only
581is only usable as a long option, hence
582.Fl s
583is only specified in
584.Fa optstring
585and
586.Fl -long-only
587is only specified in the
588.Fa longopts
589.Vt option
590array.
591.Pp
592.Bd -literal -compact
593#include <getopt.h>
594#include <stdio.h>
595#include <limits.h>
596
597enum longopt_chars {
598        LONG_ONLY = USHRT_MAX +1
599};
600
601static struct option longopts[] = {
602        { "all", no_argument, NULL, 'a' },
603        { "list", no_argument, NULL, 'l' },
604        { "long-only", no_argument, NULL, LONG_ONLY },
605        { "output", required_argument, NULL, 'o' },
606        { NULL }
607};
608
609int
610main(int argc, char *argv[])
611{
612        int ch;
613
614        while ((ch = getopt_long(argc, argv, "alo:s", longopts,
615            NULL)) != -1) {
616                switch (ch) {
617                case 'a':
618                        printf("found -a\en");
619                        break;
620                case 'l':
621                        printf("found -l\en");
622                        break;
623                case 'o':
624                        printf("found -o: %s\en", optarg);
625                        break;
626                case 's':
627                        printf("found -s\en");
628                        break;
629                case LONG_ONLY:
630                        printf("found --long-only\en");
631                        break;
632                default:
633                        break;
634                }
635        }
636
637        return (0);
638}
639.Ed
640.Sh ERRORS
641The
642.Fn getopt_long_clip
643function will fail if:
644.Bl -tag -width EINVAL
645.It Er EINVAL
646A short option is missing a corresponding long option, or vice-versa.
647.El
648.Pp
649There are no errors defined for
650.Fn getopt_long
651and
652.Fn getopt_long_only .
653.Sh IMPLEMENTATION DIFFERENCES
654While the illumos implementations of
655.Nm getopt_long
656and
657.Nm getopt_long_only
658are broadly compatible with other implementations, the following edge cases
659have historically been known to vary among implementations:
660.Bl -bullet
661.It
662The setting of
663.Va optopt
664for long options with
665.Fa flag
666!=
667.Dv NULL
668in
669.Vt struct option .
670In illumos,
671.Va optopt
672is set to 0 (since
673.Fa val
674would never be returned).
675.It
676The setting of
677.Va optarg
678for long options without an argument that are
679invoked via
680.Ql -W
681.Ql ( W\&;
682in
683.Fa optstring ) .
684illumos sets
685.Va optarg
686to the option name (the argument of
687.Ql -W ) .
688.It
689The handling of
690.Ql -W
691with an argument that is not (a prefix to) a known
692long option
693.Ql ( W\&;
694in
695.Fa optstring ) .
696illumos treats this as an error (unknown option) and returns
697.Ql \&?
698with
699.Va optopt
700set to 0 and
701.Va optarg
702set to
703.Dv NULL .
704.It
705illumos
706may not permute the argument vector at the same points in
707the calling sequence as other implementations.
708The aspects normally used by
709the caller (ordering after \-1 is returned, the value of
710.Va optind
711relative
712to current positions) are the same, though.
713(We often do fewer variable swaps.)
714.El
715.Sh INTERFACE STABILITY
716Committed
717.Sh MT-LEVEL
718Unsafe
719.Sh SEE ALSO
720.Xr getopt 3C
721.Sh BUGS
722The
723.Fa argv
724argument is not really
725.Vt const
726as its elements may be permuted (unless
727.Ev POSIXLY_CORRECT
728is set).
729