linux GNU getopt: ignore unknown optional arguments?
bash, getopt, linux
Solution
It is not possible to tell GNU getopt to ignore unknown options. If you really want that feature you will have to write your own option parser.
It is not as simple as to just ignore unknown options. How can you tell whether an unknown option takes an argument or not?
Example usage of original script:
originalscript --mode foo source
here `foo` is an argument to the option `--mode`. while `source` is a "non-option parameter" (sometimes called "positional parameter").
Example usage of wrapper script:
wrapperscript --with template --mode foo source
How can getopt in `wrapperscript` know that it should ignore `--mode` together with `foo`? If it just ignores `--mode` then `originalscript` will get `foo` as first positional parameter.
A possible workaround is to tell the users of your wrapper script to write all options intended for the original scrip after a double dash (`--`). By convention a double dash marks the end of options. GNU getopt recognizes double dash and stops parsing and returns the rest as positional parameters.
See also:
- http://wiki.bash-hackers.org/dict/terms/end_of_options
Problem
Is it possible to ignore unknown optional arguments with GNU getopt? I have a script, scriptA.sh, that has optional arguments `--optA, --optB, --optC, --optD`. I would like to write a wrapper, wrapperA, with two optional arguments, `--optX and --optY`, that calls `scriptA`. However, I don't want to declare all optional parameters of scriptA inside the wrapper. In particular, if inside `wrapperA`, I specify optional arguments with ``` getopt --longoptions optX:,optY: ``` the call ``` wrapperA --optX --optA --optB ``` returns an error ``` getopt: unknown option -- optA ``` Can GNU getopt be forced to ignore unknown arguments and place them after the '--' in its output?