linux GNU getopt: ignore unknown optional arguments? linux GNU getopt: ignore unknown optional arguments? bash bash

linux GNU getopt: ignore unknown optional arguments?


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:


I was working on a similar thing, and found this to work to stop getopt errors from bugging me with these errors. Basically just pipe the errors to oblivion.

while getopts "i:s:" opt > /dev/null 2>&1; do    case $opt in      i)        END=$OPTARG      ;;    esacdone./innerscript $*

$ ./blah.sh -s 20140503 -i 3 -a -b -c


If you want to just ignore stderr, appending 2>dev/null to the starting line of while as below is OK. I think you can use this also for getopt.

while getopts "a:p:" opt 2>/dev/nulldo    case $opt in      \?)        echo "any error comment you want" 1>&2        exit 1        ;;    esacdone