|
|
#include <unistd.h>int getopt (int argc, char *const *argv, const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
optind- index of the next option argument
opterr- disable getopt error message
optopt- value of character that caused getopt error
getopt returns the next option letter in argv that matches a letter in optstring. It supports all the rules of the command syntax standard [see intro(1)]. Since all new commands are intended to adhere to the command syntax standard, they should use getopts(1), getopt(3C), or getsubopt(3C) to parse positional parameters and check for options that are legal for that command.
optstring must contain the option letters that the command using getopt will recognize. If a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which may 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. optind is external and is initialized to 1 before the first call to getopt. When all options have been processed (that is, up to the first non-option argument), getopt returns EOF. The special option ``--'' (two hyphens) may be used to delimit the end of the options; when it is encountered, EOF is returned and ``--'' is skipped. This is useful in delimiting non-option arguments that begin with ``-'' (hyphen).
The label defined by a call to setlabel(3C) will be used if available; otherwise the name of the utility (argv[0]) will be used.
#include <unistd.h> #include <stdio.h>main (int argc, char argv) { int c; extern char optarg; extern int optind; int aflg = 0; int bflg = 0; int errflg = 0; char ofile = NULL;
while ((c = getopt(argc, argv, "abo:")) != EOF) switch (c) { case 'a': if (bflg) errflg++; else aflg++; break; case 'b': if (aflg) errflg++; else bflg++; break; case 'o': ofile = optarg; (void)printf("ofile = %s\n", ofile); break; case '?': errflg++; } if (errflg) { (void)fprintf(stderr, "usage: cmd [-a|-b] [-o<file>] files...\n"); exit (2); } for ( ; optind < argc; optind++) (void)printf("%s\n", argv[optind]); return 0; }
It is a violation of the command syntax standard [see intro(1)] for options with arguments to be grouped with other options, as in cmd -aboxxx file, where a and b are options, o is an option that requires an argument, and xxx is the argument to o. Although this syntax is permitted in the current implementation, it should not be used because it may not be supported in future releases. The correct syntax is cmd -ab -o xxx file.