'POSIX multi-value option_argument syntax

I have read https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html.

I understand that a short option_argument can look like -kvalue or -k value.

If we want to specify multiple values for the option_argument, we can write -kvalue1 -kvalue2, -k value1 -k value2, or a mix of both syntaxes.

My question:

Is -k value1 value2 valid and equivalent to the above?

Further, what about for long option_arguments? Is --key value1 value2 the same?



Solution 1:[1]

-k value1 value2 is usually equivalent to -k value1 -- value2, where value1 is the option_argument to -k, and value2 is an operand (a program argument like in echo value2 or ls value2). Were you to implement this by manipulating optind/OPTIND, you would have the following problems:

  • In -k value1 value2 ... valueN input-file, how would you know that input-file is an input file and not intended as -k input-file?
  • Does -k -z mean -k had 0 arguments, followed by the -z option, or is -z treated as an option_argument? What about -k value1 value2 -z value4?

Also, -k value1 -k value2 would typically replace value1 with value2, so it would be a good idea to document the additive behavior of -k if it were implemented. You should avoid -( and -) options. On Solaris, per its CLIP guidelines (scroll down to the Command Syntax Standard: Guidelines section), the ( and ) characters delimit long option names, like ?(help)V(version) would recognize --help as -? and --version as -V.

As for long option arguments, POSIX does not support them, whether that is -old-style arg, --gnu-style=arg, or --gnu-style arg. An optstring "-:k:" is not portable according to POSIX either because - is not alphanumeric; even if it is supported, you would also need to deal with changing optind/OPTIND in the case of --key value1 to set the key value to value1 since key is the option_argument for the - option.

If you are merely writing a utility rather than implementing getopt rules in your own option parser, an alternative would be to rely on getopt_long, keeping the implementation differences in mind; it is widely available, even if it is not specified by POSIX. You could also use a separate option parsing library (or shell function or whatever you would use in the language you're dealing with).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MemReflect