.
[coreutils.git] / lib / getopt.c
blob91f00b55bb20bf2c773df92bec11fbc709c001d6
1 /* Getopt for GNU.
2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
4 before changing it!
6 Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 1996
7 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
23 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
24 Ditto for AIX 3.2 and <stdlib.h>. */
25 #ifndef _NO_PROTO
26 #define _NO_PROTO
27 #endif
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
33 #if !defined (__STDC__) || !__STDC__
34 /* This is a separate conditional since some stdc systems
35 reject `defined (const)'. */
36 #ifndef const
37 #define const
38 #endif
39 #endif
41 #include <stdio.h>
43 /* Comment out all this code if we are using the GNU C Library, and are not
44 actually compiling the library itself. This code is part of the GNU C
45 Library, but also included in many other GNU distributions. Compiling
46 and linking in this code is a waste when using the GNU C library
47 (especially if it is a shared library). Rather than having every GNU
48 program understand `configure --with-gnu-libc' and omit the object files,
49 it is simpler to just do this in the source for each such file. */
51 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
54 /* This needs to come after some library #include
55 to get __GNU_LIBRARY__ defined. */
56 #ifdef __GNU_LIBRARY__
57 /* Don't include stdlib.h for non-GNU C libraries because some of them
58 contain conflicting prototypes for getopt. */
59 #include <stdlib.h>
60 #if defined (_LIBC) || defined (HAVE_UNISTD_H)
61 #include <unistd.h>
62 #endif
63 #endif /* GNU C library. */
65 #ifdef VMS
66 #include <unixlib.h>
67 #if HAVE_STRING_H - 0
68 #include <string.h>
69 #endif
70 #endif
72 #ifdef WIN32
73 /* It's not Unix, really. See? Capital letters. */
74 #include <windows.h>
75 #define getpid() GetCurrentProcessId()
76 #endif
78 #ifndef _
79 /* This is for other GNU distributions with internationalized messages.
80 When compiling libc, the _ macro is predefined. */
81 #ifdef HAVE_LIBINTL_H
82 # include <libintl.h>
83 # define _(msgid) gettext (msgid)
84 #else
85 # define _(msgid) (msgid)
86 #endif
87 #endif
89 /* This version of `getopt' appears to the caller like standard Unix `getopt'
90 but it behaves differently for the user, since it allows the user
91 to intersperse the options with the other arguments.
93 As `getopt' works, it permutes the elements of ARGV so that,
94 when it is done, all the options precede everything else. Thus
95 all application programs are extended to handle flexible argument order.
97 Setting the environment variable POSIXLY_CORRECT disables permutation.
98 Then the behavior is completely standard.
100 GNU application programs can use a third alternative mode in which
101 they can distinguish the relative order of options and other arguments. */
103 #include "getopt.h"
105 /* For communication from `getopt' to the caller.
106 When `getopt' finds an option that takes an argument,
107 the argument value is returned here.
108 Also, when `ordering' is RETURN_IN_ORDER,
109 each non-option ARGV-element is returned here. */
111 char *optarg = NULL;
113 /* Index in ARGV of the next element to be scanned.
114 This is used for communication to and from the caller
115 and for communication between successive calls to `getopt'.
117 On entry to `getopt', zero means this is the first call; initialize.
119 When `getopt' returns EOF, this is the index of the first of the
120 non-option elements that the caller should itself scan.
122 Otherwise, `optind' communicates from one call to the next
123 how much of ARGV has been scanned so far. */
125 /* XXX 1003.2 says this must be 1 before any call. */
126 int optind = 0;
128 /* The next char to be scanned in the option-element
129 in which the last option character we returned was found.
130 This allows us to pick up the scan where we left off.
132 If this is zero, or a null string, it means resume the scan
133 by advancing to the next ARGV-element. */
135 static char *nextchar;
137 /* Callers store zero here to inhibit the error message
138 for unrecognized options. */
140 int opterr = 1;
142 /* Set to an option character which was unrecognized.
143 This must be initialized on some systems to avoid linking in the
144 system's own getopt implementation. */
146 int optopt = '?';
148 /* Describe how to deal with options that follow non-option ARGV-elements.
150 If the caller did not specify anything,
151 the default is REQUIRE_ORDER if the environment variable
152 POSIXLY_CORRECT is defined, PERMUTE otherwise.
154 REQUIRE_ORDER means don't recognize them as options;
155 stop option processing when the first non-option is seen.
156 This is what Unix does.
157 This mode of operation is selected by either setting the environment
158 variable POSIXLY_CORRECT, or using `+' as the first character
159 of the list of option characters.
161 PERMUTE is the default. We permute the contents of ARGV as we scan,
162 so that eventually all the non-options are at the end. This allows options
163 to be given in any order, even with programs that were not written to
164 expect this.
166 RETURN_IN_ORDER is an option available to programs that were written
167 to expect options and other ARGV-elements in any order and that care about
168 the ordering of the two. We describe each non-option ARGV-element
169 as if it were the argument of an option with character code 1.
170 Using `-' as the first character of the list of option characters
171 selects this mode of operation.
173 The special argument `--' forces an end of option-scanning regardless
174 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
175 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
177 static enum
179 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
180 } ordering;
182 /* Value of POSIXLY_CORRECT environment variable. */
183 static char *posixly_correct;
185 #ifdef __GNU_LIBRARY__
186 /* We want to avoid inclusion of string.h with non-GNU libraries
187 because there are many ways it can cause trouble.
188 On some systems, it contains special magic macros that don't work
189 in GCC. */
190 #include <string.h>
191 #define my_index strchr
192 #else
194 /* Avoid depending on library functions or files
195 whose names are inconsistent. */
197 char *getenv ();
199 static char *
200 my_index (str, chr)
201 const char *str;
202 int chr;
204 while (*str)
206 if (*str == chr)
207 return (char *) str;
208 str++;
210 return 0;
213 /* If using GCC, we can safely declare strlen this way.
214 If not using GCC, it is ok not to declare it. */
215 #ifdef __GNUC__
216 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
217 That was relevant to code that was here before. */
218 #if !defined (__STDC__) || !__STDC__
219 /* gcc with -traditional declares the built-in strlen to return int,
220 and has done so at least since version 2.4.5. -- rms. */
221 extern int strlen (const char *);
222 #endif /* not __STDC__ */
223 #endif /* __GNUC__ */
225 #endif /* not __GNU_LIBRARY__ */
227 /* Handle permutation of arguments. */
229 /* Describe the part of ARGV that contains non-options that have
230 been skipped. `first_nonopt' is the index in ARGV of the first of them;
231 `last_nonopt' is the index after the last of them. */
233 static int first_nonopt;
234 static int last_nonopt;
236 /* Bash 2.0 gives us an environment variable containing flags
237 indicating ARGV elements that should not be considered arguments. */
239 static const char *nonoption_flags;
240 static int nonoption_flags_len;
242 /* Exchange two adjacent subsequences of ARGV.
243 One subsequence is elements [first_nonopt,last_nonopt)
244 which contains all the non-options that have been skipped so far.
245 The other is elements [last_nonopt,optind), which contains all
246 the options processed since those non-options were skipped.
248 `first_nonopt' and `last_nonopt' are relocated so that they describe
249 the new indices of the non-options in ARGV after they are moved. */
251 #if defined (__STDC__) && __STDC__
252 static void exchange (char **);
253 #endif
255 static void
256 exchange (argv)
257 char **argv;
259 int bottom = first_nonopt;
260 int middle = last_nonopt;
261 int top = optind;
262 char *tem;
264 /* Exchange the shorter segment with the far end of the longer segment.
265 That puts the shorter segment into the right place.
266 It leaves the longer segment in the right place overall,
267 but it consists of two parts that need to be swapped next. */
269 while (top > middle && middle > bottom)
271 if (top - middle > middle - bottom)
273 /* Bottom segment is the short one. */
274 int len = middle - bottom;
275 register int i;
277 /* Swap it with the top part of the top segment. */
278 for (i = 0; i < len; i++)
280 tem = argv[bottom + i];
281 argv[bottom + i] = argv[top - (middle - bottom) + i];
282 argv[top - (middle - bottom) + i] = tem;
284 /* Exclude the moved bottom segment from further swapping. */
285 top -= len;
287 else
289 /* Top segment is the short one. */
290 int len = top - middle;
291 register int i;
293 /* Swap it with the bottom part of the bottom segment. */
294 for (i = 0; i < len; i++)
296 tem = argv[bottom + i];
297 argv[bottom + i] = argv[middle + i];
298 argv[middle + i] = tem;
300 /* Exclude the moved top segment from further swapping. */
301 bottom += len;
305 /* Update records for the slots the non-options now occupy. */
307 first_nonopt += (optind - last_nonopt);
308 last_nonopt = optind;
311 /* Initialize the internal data when the first call is made. */
313 #if defined (__STDC__) && __STDC__
314 static const char *_getopt_initialize (const char *);
315 #endif
316 static const char *
317 _getopt_initialize (optstring)
318 const char *optstring;
320 /* Start processing options with ARGV-element 1 (since ARGV-element 0
321 is the program name); the sequence of previously skipped
322 non-option ARGV-elements is empty. */
324 first_nonopt = last_nonopt = optind = 1;
326 nextchar = NULL;
328 posixly_correct = getenv ("POSIXLY_CORRECT");
330 /* Determine how to handle the ordering of options and nonoptions. */
332 if (optstring[0] == '-')
334 ordering = RETURN_IN_ORDER;
335 ++optstring;
337 else if (optstring[0] == '+')
339 ordering = REQUIRE_ORDER;
340 ++optstring;
342 else if (posixly_correct != NULL)
343 ordering = REQUIRE_ORDER;
344 else
345 ordering = PERMUTE;
347 if (posixly_correct == NULL)
349 /* Bash 2.0 puts a special variable in the environment for each
350 command it runs, specifying which ARGV elements are the results of
351 file name wildcard expansion and therefore should not be
352 considered as options. */
353 char var[100];
354 sprintf (var, "_%d_GNU_nonoption_argv_flags_", getpid ());
355 nonoption_flags = getenv (var);
356 if (nonoption_flags == NULL)
357 nonoption_flags_len = 0;
358 else
359 nonoption_flags_len = strlen (nonoption_flags);
362 return optstring;
365 /* Scan elements of ARGV (whose length is ARGC) for option characters
366 given in OPTSTRING.
368 If an element of ARGV starts with '-', and is not exactly "-" or "--",
369 then it is an option element. The characters of this element
370 (aside from the initial '-') are option characters. If `getopt'
371 is called repeatedly, it returns successively each of the option characters
372 from each of the option elements.
374 If `getopt' finds another option character, it returns that character,
375 updating `optind' and `nextchar' so that the next call to `getopt' can
376 resume the scan with the following option character or ARGV-element.
378 If there are no more option characters, `getopt' returns `EOF'.
379 Then `optind' is the index in ARGV of the first ARGV-element
380 that is not an option. (The ARGV-elements have been permuted
381 so that those that are not options now come last.)
383 OPTSTRING is a string containing the legitimate option characters.
384 If an option character is seen that is not listed in OPTSTRING,
385 return '?' after printing an error message. If you set `opterr' to
386 zero, the error message is suppressed but we still return '?'.
388 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
389 so the following text in the same ARGV-element, or the text of the following
390 ARGV-element, is returned in `optarg'. Two colons mean an option that
391 wants an optional arg; if there is text in the current ARGV-element,
392 it is returned in `optarg', otherwise `optarg' is set to zero.
394 If OPTSTRING starts with `-' or `+', it requests different methods of
395 handling the non-option ARGV-elements.
396 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
398 Long-named options begin with `--' instead of `-'.
399 Their names may be abbreviated as long as the abbreviation is unique
400 or is an exact match for some defined option. If they have an
401 argument, it follows the option name in the same ARGV-element, separated
402 from the option name by a `=', or else the in next ARGV-element.
403 When `getopt' finds a long-named option, it returns 0 if that option's
404 `flag' field is nonzero, the value of the option's `val' field
405 if the `flag' field is zero.
407 The elements of ARGV aren't really const, because we permute them.
408 But we pretend they're const in the prototype to be compatible
409 with other systems.
411 LONGOPTS is a vector of `struct option' terminated by an
412 element containing a name which is zero.
414 LONGIND returns the index in LONGOPT of the long-named option found.
415 It is only valid when a long-named option has been found by the most
416 recent call.
418 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
419 long-named options. */
422 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
423 int argc;
424 char *const *argv;
425 const char *optstring;
426 const struct option *longopts;
427 int *longind;
428 int long_only;
430 optarg = NULL;
432 if (optind == 0)
434 optstring = _getopt_initialize (optstring);
435 optind = 1; /* Don't scan ARGV[0], the program name. */
438 /* Test whether ARGV[optind] points to a non-option argument.
439 Either it does not have option syntax, or there is an environment flag
440 from the shell indicating it is not an option. */
441 #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
442 || (optind < nonoption_flags_len \
443 && nonoption_flags[optind] == '1'))
445 if (nextchar == NULL || *nextchar == '\0')
447 /* Advance to the next ARGV-element. */
449 /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
450 moved back by the user (who may also have changed the arguments). */
451 if (last_nonopt > optind)
452 last_nonopt = optind;
453 if (first_nonopt > optind)
454 first_nonopt = optind;
456 if (ordering == PERMUTE)
458 /* If we have just processed some options following some non-options,
459 exchange them so that the options come first. */
461 if (first_nonopt != last_nonopt && last_nonopt != optind)
462 exchange ((char **) argv);
463 else if (last_nonopt != optind)
464 first_nonopt = optind;
466 /* Skip any additional non-options
467 and extend the range of non-options previously skipped. */
469 while (optind < argc && NONOPTION_P)
470 optind++;
471 last_nonopt = optind;
474 /* The special ARGV-element `--' means premature end of options.
475 Skip it like a null option,
476 then exchange with previous non-options as if it were an option,
477 then skip everything else like a non-option. */
479 if (optind != argc && !strcmp (argv[optind], "--"))
481 optind++;
483 if (first_nonopt != last_nonopt && last_nonopt != optind)
484 exchange ((char **) argv);
485 else if (first_nonopt == last_nonopt)
486 first_nonopt = optind;
487 last_nonopt = argc;
489 optind = argc;
492 /* If we have done all the ARGV-elements, stop the scan
493 and back over any non-options that we skipped and permuted. */
495 if (optind == argc)
497 /* Set the next-arg-index to point at the non-options
498 that we previously skipped, so the caller will digest them. */
499 if (first_nonopt != last_nonopt)
500 optind = first_nonopt;
501 return EOF;
504 /* If we have come to a non-option and did not permute it,
505 either stop the scan or describe it to the caller and pass it by. */
507 if (NONOPTION_P)
509 if (ordering == REQUIRE_ORDER)
510 return EOF;
511 optarg = argv[optind++];
512 return 1;
515 /* We have found another option-ARGV-element.
516 Skip the initial punctuation. */
518 nextchar = (argv[optind] + 1
519 + (longopts != NULL && argv[optind][1] == '-'));
522 /* Decode the current option-ARGV-element. */
524 /* Check whether the ARGV-element is a long option.
526 If long_only and the ARGV-element has the form "-f", where f is
527 a valid short option, don't consider it an abbreviated form of
528 a long option that starts with f. Otherwise there would be no
529 way to give the -f short option.
531 On the other hand, if there's a long option "fubar" and
532 the ARGV-element is "-fu", do consider that an abbreviation of
533 the long option, just like "--fu", and not "-f" with arg "u".
535 This distinction seems to be the most useful approach. */
537 if (longopts != NULL
538 && (argv[optind][1] == '-'
539 || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
541 char *nameend;
542 const struct option *p;
543 const struct option *pfound = NULL;
544 int exact = 0;
545 int ambig = 0;
546 int indfound;
547 int option_index;
549 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
550 /* Do nothing. */ ;
552 #ifdef lint /* Suppress `used before initialized' warning. */
553 indfound = 0;
554 #endif
556 /* Test all long options for either exact match
557 or abbreviated matches. */
558 for (p = longopts, option_index = 0; p->name; p++, option_index++)
559 if (!strncmp (p->name, nextchar, nameend - nextchar))
561 if (nameend - nextchar == strlen (p->name))
563 /* Exact match found. */
564 pfound = p;
565 indfound = option_index;
566 exact = 1;
567 break;
569 else if (pfound == NULL)
571 /* First nonexact match found. */
572 pfound = p;
573 indfound = option_index;
575 else
576 /* Second or later nonexact match found. */
577 ambig = 1;
580 if (ambig && !exact)
582 if (opterr)
583 fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
584 argv[0], argv[optind]);
585 nextchar += strlen (nextchar);
586 optind++;
587 optopt = 0;
588 return '?';
591 if (pfound != NULL)
593 option_index = indfound;
594 optind++;
595 if (*nameend)
597 /* Don't test has_arg with >, because some C compilers don't
598 allow it to be used on enums. */
599 if (pfound->has_arg)
600 optarg = nameend + 1;
601 else
603 if (opterr)
604 if (argv[optind - 1][1] == '-')
605 /* --option */
606 fprintf (stderr,
607 _("%s: option `--%s' doesn't allow an argument\n"),
608 argv[0], pfound->name);
609 else
610 /* +option or -option */
611 fprintf (stderr,
612 _("%s: option `%c%s' doesn't allow an argument\n"),
613 argv[0], argv[optind - 1][0], pfound->name);
615 nextchar += strlen (nextchar);
617 optopt = pfound->val;
618 return '?';
621 else if (pfound->has_arg == 1)
623 if (optind < argc)
624 optarg = argv[optind++];
625 else
627 if (opterr)
628 fprintf (stderr,
629 _("%s: option `%s' requires an argument\n"),
630 argv[0], argv[optind - 1]);
631 nextchar += strlen (nextchar);
632 optopt = pfound->val;
633 return optstring[0] == ':' ? ':' : '?';
636 nextchar += strlen (nextchar);
637 if (longind != NULL)
638 *longind = option_index;
639 if (pfound->flag)
641 *(pfound->flag) = pfound->val;
642 return 0;
644 return pfound->val;
647 /* Can't find it as a long option. If this is not getopt_long_only,
648 or the option starts with '--' or is not a valid short
649 option, then it's an error.
650 Otherwise interpret it as a short option. */
651 if (!long_only || argv[optind][1] == '-'
652 || my_index (optstring, *nextchar) == NULL)
654 if (opterr)
656 if (argv[optind][1] == '-')
657 /* --option */
658 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
659 argv[0], nextchar);
660 else
661 /* +option or -option */
662 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
663 argv[0], argv[optind][0], nextchar);
665 nextchar = (char *) "";
666 optind++;
667 optopt = 0;
668 return '?';
672 /* Look at and handle the next short option-character. */
675 char c = *nextchar++;
676 char *temp = my_index (optstring, c);
678 /* Increment `optind' when we start to process its last character. */
679 if (*nextchar == '\0')
680 ++optind;
682 if (temp == NULL || c == ':')
684 if (opterr)
686 if (posixly_correct)
687 /* 1003.2 specifies the format of this message. */
688 fprintf (stderr, _("%s: illegal option -- %c\n"),
689 argv[0], c);
690 else
691 fprintf (stderr, _("%s: invalid option -- %c\n"),
692 argv[0], c);
694 optopt = c;
695 return '?';
697 if (temp[1] == ':')
699 if (temp[2] == ':')
701 /* This is an option that accepts an argument optionally. */
702 if (*nextchar != '\0')
704 optarg = nextchar;
705 optind++;
707 else
708 optarg = NULL;
709 nextchar = NULL;
711 else
713 /* This is an option that requires an argument. */
714 if (*nextchar != '\0')
716 optarg = nextchar;
717 /* If we end this ARGV-element by taking the rest as an arg,
718 we must advance to the next element now. */
719 optind++;
721 else if (optind == argc)
723 if (opterr)
725 /* 1003.2 specifies the format of this message. */
726 fprintf (stderr,
727 _("%s: option requires an argument -- %c\n"),
728 argv[0], c);
730 optopt = c;
731 if (optstring[0] == ':')
732 c = ':';
733 else
734 c = '?';
736 else
737 /* We already incremented `optind' once;
738 increment it again when taking next ARGV-elt as argument. */
739 optarg = argv[optind++];
740 nextchar = NULL;
743 return c;
748 getopt (argc, argv, optstring)
749 int argc;
750 char *const *argv;
751 const char *optstring;
753 return _getopt_internal (argc, argv, optstring,
754 (const struct option *) 0,
755 (int *) 0,
759 #endif /* _LIBC or not __GNU_LIBRARY__. */
761 #ifdef TEST
763 /* Compile with -DTEST to make an executable for use in testing
764 the above definition of `getopt'. */
767 main (argc, argv)
768 int argc;
769 char **argv;
771 int c;
772 int digit_optind = 0;
774 while (1)
776 int this_option_optind = optind ? optind : 1;
778 c = getopt (argc, argv, "abc:d:0123456789");
779 if (c == EOF)
780 break;
782 switch (c)
784 case '0':
785 case '1':
786 case '2':
787 case '3':
788 case '4':
789 case '5':
790 case '6':
791 case '7':
792 case '8':
793 case '9':
794 if (digit_optind != 0 && digit_optind != this_option_optind)
795 printf ("digits occur in two different argv-elements.\n");
796 digit_optind = this_option_optind;
797 printf ("option %c\n", c);
798 break;
800 case 'a':
801 printf ("option a\n");
802 break;
804 case 'b':
805 printf ("option b\n");
806 break;
808 case 'c':
809 printf ("option c with value `%s'\n", optarg);
810 break;
812 case '?':
813 break;
815 default:
816 printf ("?? getopt returned character code 0%o ??\n", c);
820 if (optind < argc)
822 printf ("non-option ARGV-elements: ");
823 while (optind < argc)
824 printf ("%s ", argv[optind++]);
825 printf ("\n");
828 exit (0);
831 #endif /* TEST */