# getopt

## PROLOG



           This manual page is part of the POSIX Programmer's Manual.  The
           Linux implementation of this interface may differ (consult the
           corresponding Linux manual page for details of Linux behavior), or
           the interface may not be implemented on Linux.
    


## NAME



           getopt, optarg, opterr, optind, optopt — command option parsing
    


## SYNOPSIS



           #include <unistd.h>
    
           int getopt(int _argc_ , char * const _argv_[], const char *_optstring_);
           extern char *optarg;
           extern int opterr, optind, optopt;
    


## DESCRIPTION



           The _getopt_() function is a command-line parser that shall follow
           Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 in the Base
           Definitions volume of POSIX.1‐2017, _Section 12.2_ , _Utility Syntax_
           _Guidelines_.
    
           The parameters _argc_ and _argv_ are the argument count and argument
           array as passed to _main_() (see _exec_()).  The argument _optstring_ is
           a string of recognized option characters; if a character is
           followed by a <colon>, the option takes an argument. All option
           characters allowed by Utility Syntax Guideline 3 are allowed in
           _optstring_.  The implementation may accept other characters as an
           extension.
    
           The variable _optind_ is the index of the next element of the _argv_[]
           vector to be processed. It shall be initialized to 1 by the
           system, and _getopt_() shall update it when it finishes with each
           element of _argv_[].  If the application sets _optind_ to zero before
           calling _getopt_(), the behavior is unspecified. When an element of
           _argv_[] contains multiple option characters, it is unspecified how
           _getopt_() determines which options have already been processed.
    
           The _getopt_() function shall return the next option character (if
           one is found) from _argv_ that matches a character in _optstring_ , if
           there is one that matches. If the option takes an argument,
           _getopt_() shall set the variable _optarg_ to point to the option-
           argument as follows:
    
            1. If the option was the last character in the string pointed to
               by an element of _argv_ , then _optarg_ shall contain the next
               element of _argv_ , and _optind_ shall be incremented by 2. If the
               resulting value of _optind_ is greater than _argc_ , this indicates
               a missing option-argument, and _getopt_() shall return an error
               indication.
    
            2. Otherwise, _optarg_ shall point to the string following the
               option character in that element of _argv_ , and _optind_ shall be
               incremented by 1.
    
           If, when _getopt_() is called:
    
                _argv_[optind]  is a null pointer
               *_argv_[optind]  is not the character -
                _argv_[optind]  points to the string "-"
    
           _getopt_() shall return -1 without changing _optind_.  If:
    
               _argv_[optind]   points to the string "--"
    
           _getopt_() shall return -1 after incrementing _optind_.
    
           If _getopt_() encounters an option character that is not contained
           in _optstring_ , it shall return the <question-mark> (**'?'**)
           character. If it detects a missing option-argument, it shall
           return the <colon> character (**':'**) if the first character of
           _optstring_ was a <colon>, or a <question-mark> character (**'?'**)
           otherwise. In either case, _getopt_() shall set the variable _optopt_
           to the option character that caused the error. If the application
           has not set the variable _opterr_ to 0 and the first character of
           _optstring_ is not a <colon>, _getopt_() shall also print a diagnostic
           message to _stderr_ in the format specified for the _getopts_ utility,
           unless the _stderr_ stream has wide orientation, in which case the
           behavior is undefined.
    
           The _getopt_() function need not be thread-safe.
    


## RETURN VALUE



           The _getopt_() function shall return the next option character
           specified on the command line.
    
           A <colon> (**':'**) shall be returned if _getopt_() detects a missing
           argument and the first character of _optstring_ was a <colon> (**':'**).
    
           A <question-mark> (**'?'**)  shall be returned if _getopt_() encounters
           an option character not in _optstring_ or detects a missing argument
           and the first character of _optstring_ was not a <colon> (**':'**).
    
           Otherwise, _getopt_() shall return -1 when all command line options
           are parsed.
    


## ERRORS



           If the application has not set the variable _opterr_ to 0, the first
           character of _optstring_ is not a <colon>, and a write error occurs
           while _getopt_() is printing a diagnostic message to _stderr_ , then
           the error indicator for _stderr_ shall be set; but _getopt_() shall
           still succeed and the value of _errno_ after _getopt_() is
           unspecified.
    
           _The following sections are informative._
    


## EXAMPLES



       **Parsing Command Line Options**
           The following code fragment shows how you might process the
           arguments for a utility that can take the mutually-exclusive
           options _a_ and _b_ and the options _f_ and _o_ , both of which require
           arguments:
    
               #include <stdio.h>
               #include <stdlib.h>
               #include <unistd.h>
    
               int
               main(int argc, char *argv[ ])
               {
                   int c;
                   int bflg = 0, aflg = 0, errflg = 0;
                   char *ifile;
                   char *ofile;
                   . . .
                   while ((c = getopt(argc, argv, ":abf:o:")) != -1) {
                       switch(c) {
                       case 'a':
                           if (bflg)
                               errflg++;
                           else
                               aflg++;
                           break;
                       case 'b':
                           if (aflg)
                               errflg++;
                           else
                               bflg++;
                           break;
                       case 'f':
                           ifile = optarg;
                           break;
                       case 'o':
                           ofile = optarg;
                           break;
                       case ':':       /* -f or -o without operand */
                           fprintf(stderr,
                               "Option -%c requires an operand\n", optopt);
                           errflg++;
                           break;
                       case '?':
                           fprintf(stderr,
                               "Unrecognized option: '-%c'\n", optopt);
                           errflg++;
                       }
                   }
                   if (errflg) {
                       fprintf(stderr, "usage: . . . ");
                       exit(2);
                   }
                   for ( ; optind < argc; optind++) {
                       if (access(argv[optind], R_OK)) {
                   . . .
               }
    
           This code accepts any of the following as equivalent:
    
               cmd -ao arg path path
               cmd -a -o arg path path
               cmd -o arg -a path path
               cmd -a -o arg -- path path
               cmd -a -oarg path path
               cmd -aoarg path path
    
       **Selecting Options from the Command Line**
           The following example selects the type of database routines the
           user wants to use based on the _Options_ argument.
    
               #include <unistd.h>
               #include <string.h>
               ...
               const char *Options = "hdbtl";
               ...
               int dbtype, c;
               char *st;
               ...
               dbtype = 0;
               while ((c = getopt(argc, argv, Options)) != -1) {
                   if ((st = strchr(Options, c)) != NULL) {
                       dbtype = st - Options;
                       break;
                   }
               }
    


## APPLICATION USAGE



           The _getopt_() function is only required to support option
           characters included in Utility Syntax Guideline 3. Many historical
           implementations of _getopt_() support other characters as options.
           This is an allowed extension, but applications that use extensions
           are not maximally portable. Note that support for multi-byte
           option characters is only possible when such characters can be
           represented as type **int**.
    
           Applications which use wide-character output functions with _stderr_
           should ensure that any calls to _getopt_() do not write to _stderr_ ,
           either by setting _opterr_ to 0 or by ensuring the first character
           of _optstring_ is always a <colon>.
    
           While _ferror_(_stderr_) may be used to detect failures to write a
           diagnostic to _stderr_ when _getopt_() returns **'?'** , the value of _errno_
           is unspecified in such a condition. Applications desiring more
           control over handling write failures should set _opterr_ to 0 and
           independently perform output to _stderr_ , rather than relying on
           _getopt_() to do the output.
    


## RATIONALE



           The _optopt_ variable represents historical practice and allows the
           application to obtain the identity of the invalid option.
    
           The description has been written to make it clear that _getopt_(),
           like the _getopts_ utility, deals with option-arguments whether
           separated from the option by <blank> characters or not. Note that
           the requirements on _getopt_() and _getopts_ are more stringent than
           the Utility Syntax Guidelines.
    
           The _getopt_() function shall return -1, rather than EOF, so that
           _< stdio.h>_ is not required.
    
           The special significance of a <colon> as the first character of
           _optstring_ makes _getopt_() consistent with the _getopts_ utility. It
           allows an application to make a distinction between a missing
           argument and an incorrect option letter without having to examine
           the option letter. It is true that a missing argument can only be
           detected in one case, but that is a case that has to be
           considered.
    


## FUTURE DIRECTIONS



           None.
    


* * *