man(1) Manual page archive


     GETOPT(3)                                               GETOPT(3)

     NAME
          getopt - get option letter from argv

     SYNOPSIS
          int getopt (argc, argv, optstring)
          int argc;
          char **argv;
          char *optstring;
          extern char *optarg;
          extern int optind;

     DESCRIPTION
          Getopt returns the next option letter in argv that matches a
          letter in optstring. Optstring is a string of recognized
          option letters; if a letter is followed by a colon, the
          option is expected to have an argument which may or may not
          be separated from it by white space.  Optarg is set to point
          to the start of the option argument on return from getopt.

          Getopt places in optind the argv index of the next argument
          to be processed.  Since optind is external, it is normally
          initialized to zero automatically before the first call to
          getopt.

          Option letters appear in nonempty clusters preceded by `-'.
          When all options have been processed (i.e., up to the first
          non-option argument), getopt returns EOF.  The special
          option `--' may be used to delimit the end of the options;
          EOF will be returned, and `--' will be skipped.

     DIAGNOSTICS
          Getopt prints an error message on stderr and returns a ques-
          tion mark ('?') when it encounters an option letter not
          included in optstring.

     EXAMPLE
          This fragment processes arguments for a command that can
          take option a and option f, which requires an argument.

               main (argc, argv) char **argv;
               {
                    int c;
                    extern int optind;
                    extern char **optarg, **ifile;
                    while ((c = getopt (argc, argv, "af:")) != -1)
                         switch (c) {
                         case 'a': aflg++;
                                   break;
                         case 'f': ifile = optarg;
                                   break;

     GETOPT(3)                                               GETOPT(3)

                         case '?': errflg++;
                         }
                    if (errflg) {
                         fprintf (stderr, "usage: . . . ");
                         exit (2);
                    }
                    for( ; optind < argc; optind++) {
                         if (access (argv[optind], 4)) {
                    ...