2 * getopt.c - Enhanced implementation of BSD getopt(1)
3 * Copyright (c) 1997-2014 Frodo Looijaard <frodo@frodo.looijaard.name>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Version 1.0-b4: Tue Sep 23 1997. First public release.
22 * Version 1.0: Wed Nov 19 1997.
23 * Bumped up the version number to 1.0
24 * Fixed minor typo (CSH instead of TCSH)
25 * Version 1.0.1: Tue Jun 3 1998
26 * Fixed sizeof instead of strlen bug
27 * Bumped up the version number to 1.0.1
28 * Version 1.0.2: Thu Jun 11 1998 (not present)
29 * Fixed gcc-2.8.1 warnings
30 * Fixed --version/-V option (not present)
31 * Version 1.0.5: Tue Jun 22 1999
32 * Make -u option work (not present)
33 * Version 1.0.6: Tue Jun 27 2000
34 * No important changes
35 * Version 1.1.0: Tue Jun 30 2000
36 * Added NLS support (partly written by Arkadiusz MiĆkiewicz
37 * <misiek@pld.org.pl>)
38 * Version 1.1.4: Mon Nov 7 2005
39 * Fixed a few type's in the manpage
40 * Version 1.1.5: Sun Aug 12 2012
41 * Sync with util-linux-2.21, fixed build problems, many new translations
42 * Version 1.1.6: Mon Nov 24 2014
43 * Sync with util-linux git 20141120, detect ambiguous long options, fix
44 * backslash problem in tcsh
48 * 0) No errors, successful operation.
49 * 1) getopt(3) returned an error.
50 * 2) A problem with parameter parsing for getopt(1).
51 * 3) Internal error, out of memory
54 #define GETOPT_EXIT_CODE 1
55 #define PARAMETER_EXIT_CODE 2
56 #define XALLOC_EXIT_CODE 3
57 #define CLOSE_EXIT_CODE XALLOC_EXIT_CODE
58 #define TEST_EXIT_CODE 4
66 #ifdef HAVE_SYS_PARAM_H
67 # include <sys/param.h> /* BSD */
70 #include "closestream.h"
74 /* NON_OPT is the code that is returned getopt(3) when a non-option is
75 * found in 'char optstring[]="-abc...";', e.g., it begins by '-' */
77 /* LONG_OPT is the code that is returned when a long option is found. */
80 /* The shells recognized. */
81 typedef enum { BASH
, TCSH
} shell_t
;
83 struct getopt_control
{
84 shell_t shell
; /* the shell we generate output for */
85 char *optstr
; /* getopt(3) optstring */
87 struct option
*long_options
; /* long options */
88 int long_options_length
; /* length of options array */
89 int long_options_nr
; /* number of used elements in array */
91 compatible
:1, /* compatibility mode for 'difficult' programs */
92 quiet_errors
:1, /* print errors */
93 quiet_output
:1, /* print output */
94 quote
:1; /* quote output */
97 enum { REALLOC_INCREMENT
= 8 };
99 /* Allow changing which getopt is in use with function pointer. */
100 static int (*getopt_long_fp
) (int argc
, char *const *argv
, const char *optstr
,
101 const struct option
* longopts
, int *longindex
);
104 * This function 'normalizes' a single argument: it puts single quotes
105 * around it and escapes other special characters. If quote is false, it
106 * just returns its argument.
108 * Bash only needs special treatment for single quotes; tcsh also recognizes
109 * exclamation marks within single quotes, and nukes whitespace. This
110 * function returns a pointer to a buffer that is overwritten by each call.
112 static void print_normalized(const struct getopt_control
*ctl
, const char *arg
)
115 const char *argptr
= arg
;
124 * Each character in arg may take up to four characters in the
125 * result: For a quote we need a closing quote, a backslash, a quote
126 * and an opening quote! We need also the global opening and closing
127 * quote, and one extra character for '\0'.
129 buf
= xmalloc(strlen(arg
) * 4 + 3);
132 for (*bufptr
++ = '\''; *argptr
; argptr
++) {
133 if (ctl
->shell
== TCSH
) {
136 /* Backslash: replace it with: '\\' */
141 /* Exclamation mark: replace it with: \! */
148 /* Newline: replace it with: \n */
153 if (isspace(*argptr
)) {
154 /* Non-newline whitespace: replace it with \<ws> */
162 if (*argptr
== '\'') {
163 /* Quote: replace it with: '\'' */
180 * Generate the output. argv[0] is the program name (used for reporting errors).
181 * argv[1..] contains the options to be parsed. argc must be the number of
182 * elements in argv (ie. 1 if there are no options, only the program name),
183 * optstr must contain the short options, and longopts the long options.
184 * Other settings are found in global variables.
186 static int generate_output(struct getopt_control
*ctl
, char *argv
[], int argc
)
188 int exit_code
= EXIT_SUCCESS
; /* Assume everything will be OK */
193 if (ctl
->quiet_errors
)
194 /* No error reporting from getopt(3) */
196 /* Reset getopt(3) */
201 (argc
, argv
, ctl
->optstr
,
202 (const struct option
*)ctl
->long_options
, &longindex
)))
204 if (opt
== '?' || opt
== ':')
205 exit_code
= GETOPT_EXIT_CODE
;
206 else if (!ctl
->quiet_output
) {
209 printf(" --%s", ctl
->long_options
[longindex
].name
);
210 if (ctl
->long_options
[longindex
].has_arg
)
211 print_normalized(ctl
, optarg
? optarg
: "");
214 print_normalized(ctl
, optarg
? optarg
: "");
218 charptr
= strchr(ctl
->optstr
, opt
);
219 if (charptr
!= NULL
&& *++charptr
== ':')
220 print_normalized(ctl
, optarg
? optarg
: "");
224 if (!ctl
->quiet_output
) {
226 while (optind
< argc
)
227 print_normalized(ctl
, argv
[optind
++]);
230 for (longindex
= 0; longindex
< ctl
->long_options_nr
; longindex
++)
231 free((char *)ctl
->long_options
[longindex
].name
);
232 free(ctl
->long_options
);
239 * Report an error when parsing getopt's own arguments. If message is NULL,
240 * we already sent a message, we just exit with a helpful hint.
242 static void __attribute__ ((__noreturn__
)) parse_error(const char *message
)
245 warnx("%s", message
);
246 errtryhelp(PARAMETER_EXIT_CODE
);
250 /* Register a long option. The contents of name is copied. */
251 static void add_longopt(struct getopt_control
*ctl
, const char *name
, int has_arg
)
254 int nr
= ctl
->long_options_nr
;
256 if (ctl
->long_options_nr
== ctl
->long_options_length
) {
257 ctl
->long_options_length
+= REALLOC_INCREMENT
;
258 ctl
->long_options
= xrealloc(ctl
->long_options
,
259 sizeof(struct option
) *
260 ctl
->long_options_length
);
264 ctl
->long_options
[nr
].has_arg
= has_arg
;
265 ctl
->long_options
[nr
].flag
= &flag
;
266 ctl
->long_options
[nr
].val
= ctl
->long_options_nr
;
267 ctl
->long_options
[nr
].name
= xstrdup(name
);
269 /* lets use add_longopt(ct, NULL, 0) to terminate the array */
270 ctl
->long_options
[nr
].name
= NULL
;
271 ctl
->long_options
[nr
].has_arg
= 0;
272 ctl
->long_options
[nr
].flag
= NULL
;
273 ctl
->long_options
[nr
].val
= 0;
279 * Register several long options. options is a string of long options,
280 * separated by commas or whitespace. This nukes options!
282 static void add_long_options(struct getopt_control
*ctl
, char *options
)
285 char *tokptr
= strtok(options
, ", \t\n");
288 size_t len
= strlen(tokptr
);
290 arg_opt
= no_argument
;
292 if (tokptr
[len
- 1] == ':') {
293 if (tokptr
[len
- 2] == ':') {
294 tokptr
[len
- 2] = '\0';
295 arg_opt
= optional_argument
;
297 tokptr
[len
- 1] = '\0';
298 arg_opt
= required_argument
;
302 ("empty long option after "
303 "-l or --long argument"));
305 add_longopt(ctl
, tokptr
, arg_opt
);
306 ctl
->long_options_nr
++;
308 tokptr
= strtok(NULL
, ", \t\n");
310 add_longopt(ctl
, NULL
, 0); /* ensure long_options[] is not full */
313 static shell_t
shell_type(const char *new_shell
)
315 if (!strcmp(new_shell
, "bash"))
317 if (!strcmp(new_shell
, "sh"))
319 if (!strcmp(new_shell
, "tcsh"))
321 if (!strcmp(new_shell
, "csh"))
323 parse_error(_("unknown shell after -s or --shell argument"));
326 static void __attribute__((__noreturn__
)) usage(void)
328 fputs(USAGE_HEADER
, stdout
);
330 " %1$s <optstring> <parameters>\n"
331 " %1$s [options] [--] <optstring> <parameters>\n"
332 " %1$s [options] -o|--options <optstring> [options] [--] <parameters>\n"),
333 program_invocation_short_name
);
335 fputs(USAGE_SEPARATOR
, stdout
);
336 fputs(_("Parse command options.\n"), stdout
);
338 fputs(USAGE_OPTIONS
, stdout
);
339 fputs(_(" -a, --alternative allow long options starting with single -\n"), stdout
);
340 fputs(_(" -l, --longoptions <longopts> the long options to be recognized\n"), stdout
);
341 fputs(_(" -n, --name <progname> the name under which errors are reported\n"), stdout
);
342 fputs(_(" -o, --options <optstring> the short options to be recognized\n"), stdout
);
343 fputs(_(" -q, --quiet disable error reporting by getopt(3)\n"), stdout
);
344 fputs(_(" -Q, --quiet-output no normal output\n"), stdout
);
345 fputs(_(" -s, --shell <shell> set quoting conventions to those of <shell>\n"), stdout
);
346 fputs(_(" -T, --test test for getopt(1) version\n"), stdout
);
347 fputs(_(" -u, --unquoted do not quote the output\n"), stdout
);
348 fputs(USAGE_SEPARATOR
, stdout
);
349 printf(USAGE_HELP_OPTIONS(31));
350 printf(USAGE_MAN_TAIL("getopt(1)"));
354 int main(int argc
, char *argv
[])
356 struct getopt_control ctl
= {
362 /* Stop scanning as soon as a non-option argument is found! */
363 static const char *shortopts
= "+ao:l:n:qQs:TuhV";
364 static const struct option longopts
[] = {
365 {"options", required_argument
, NULL
, 'o'},
366 {"longoptions", required_argument
, NULL
, 'l'},
367 {"quiet", no_argument
, NULL
, 'q'},
368 {"quiet-output", no_argument
, NULL
, 'Q'},
369 {"shell", required_argument
, NULL
, 's'},
370 {"test", no_argument
, NULL
, 'T'},
371 {"unquoted", no_argument
, NULL
, 'u'},
372 {"help", no_argument
, NULL
, 'h'},
373 {"alternative", no_argument
, NULL
, 'a'},
374 {"name", required_argument
, NULL
, 'n'},
375 {"version", no_argument
, NULL
, 'V'},
379 setlocale(LC_ALL
, "");
380 bindtextdomain(PACKAGE
, LOCALEDIR
);
382 close_stdout_atexit();
384 if (getenv("GETOPT_COMPATIBLE"))
388 if (ctl
.compatible
) {
390 * For some reason, the original getopt gave no
391 * error when there were no arguments.
396 parse_error(_("missing optstring argument"));
399 add_longopt(&ctl
, NULL
, 0); /* init */
400 getopt_long_fp
= getopt_long
;
402 if (argv
[1][0] != '-' || ctl
.compatible
) {
404 ctl
.optstr
= xmalloc(strlen(argv
[1]) + 1);
405 strcpy(ctl
.optstr
, argv
[1] + strspn(argv
[1], "-+"));
407 return generate_output(&ctl
, argv
+ 1, argc
- 1);
411 getopt_long(argc
, argv
, shortopts
, longopts
, NULL
)) != EOF
)
414 getopt_long_fp
= getopt_long_only
;
418 ctl
.optstr
= xstrdup(optarg
);
421 add_long_options(&ctl
, optarg
);
425 ctl
.name
= xstrdup(optarg
);
428 ctl
.quiet_errors
= 1;
431 ctl
.quiet_output
= 1;
434 ctl
.shell
= shell_type(optarg
);
437 free(ctl
.long_options
);
438 return TEST_EXIT_CODE
;
444 print_version(EXIT_SUCCESS
);
451 parse_error(_("internal error, contact the author."));
456 parse_error(_("missing optstring argument"));
458 ctl
.optstr
= xstrdup(argv
[optind
]);
464 argv
[optind
- 1] = ctl
.name
;
465 #if defined (HAVE_SETPROGNAME) && !defined (__linux__)
466 setprogname(ctl
.name
);
469 argv
[optind
- 1] = argv
[0];
471 return generate_output(&ctl
, argv
+ optind
- 1, argc
- optind
+ 1);