getopt_long

  • Version 3.5 and earlier:getopt_long() function not available.
  • Version 4.0 and later: getopt_long() function available.

Description

Breaks up command lines for easy parsing and to check for legal options. This function examines a list of arguments for any combination of short-style or long-style options.

A short option consists of a dash followed by a single letter and possibly a parameter. For example, in the command command –a –b name –c, –a and -c are short options with no extra parameter, and -b is a short option with the parameter name.

A long option consists of two dashes followed by a name and possibly a parameter. For example, in the command command –-option1 --option2=2 –-option3 parameter –-option4, --option1 and --option4 are long options with no parameters, and --option2 and --option3 are options with extra parameters.

On the first invocation, it examines the first argument. On subsequent invocations, it picks up from where it left off and examines the next argument.

Syntax

result = getopt_long(argc, argv, short-option-string, long-option-list)

Arguments

argc Required. Number. The number of entries that are in the argument array list argv.
argv Required. List. The argument array to process.
short-option-string Required. A string that contains valid options. This list contains the letters for the short options. Each letter can be followed by a single colon (:) to indicate a required argument if the option is found. Each letter can be followed by two colons (::) to indicate an optional argument to the option. The leading characters of the short option string can modify the search characteristics as follows: A leading + stops parsing as soon as the first non-option parameter is found that is not an option argument. All other parameters are treated as non-option strings. A leading returns non-option parameters at the place where they are found.
long-option-list Required. List. A list of strings that contains the long options. Each parameter can be followed by a single colon (:) to indicate it has a required parameter, or two colons (::) to indicate that it may have an optional parameter.

Return Values

If a valid option is found, then the function returns that option. If an optional or required argument is associated with the option, then the policy variable optarg contains the value of that argument.

If no valid option is found, or if a required argument is missing, then a question mark (?) is returned. The variable optchar is set to the letter of the problem option.

When the end of the argument list is found, an empty string, "", is returned.

The variable optind is set to the subscript of the next string in the argv list.

result = getopt_long(argc, argv, "ab:c", {"long1", "long2:"});

This example examines the list of augments in argv looking for –a or –c without a parameter, –b with a parameter, --long1 without a parameter, or --long2 with a parameter.

For more information, see the following: