Linux GNU getopt: ignore unknown optional arguments?

Is it possible to ignore unknown optional arguments with GNU getopt?

I have a script, scriptA.sh that takes the optional arguments --optA, --optB, --optC, --optD .

I would like to write wrapper, wrapperA, with two optional arguments, --optX and --optY , which calls scriptA . However, I do not want to declare all optional scriptA parameters inside the shell.

In particular, if inside wrapperA , I specify optional arguments with

 getopt --longoptions optX:,optY: 

call

 wrapperA --optX --optA --optB 

returns an error

 getopt: unknown option -- optA 

Is it possible to get GNU getopt to ignore unknown arguments and put them after '-' in its output?

+7
linux bash getopt
source share
2 answers

Unable to tell GNU getopt to ignore unknown parameters. If you really need this feature, you will have to write your own parameter parser.

It is not as simple as ignoring unknown parameters. How can you determine if an unknown parameter accepts an argument or not?

An example of using the original script:

 originalscript --mode foo source 

here foo is an argument to the --mode option. while source is an "optional parameter" (sometimes called a "positional parameter").

An example of using a wrapper script:

 wrapperscript --with template --mode foo source 

How does getopt in wrapperscript know that it should ignore --mode along with foo ? If it simply ignores --mode , then originalscript will get foo as the first positional parameter.

A possible workaround is to tell the users of your shell script to write all the parameters intended for the source script after a double dash ( -- ). By convention, a double dash marks the end of the options. GNU getopt recognizes a double dash and stops parsing and returns the rest as positional parameters.

See also:

+5
source share

I worked on a similar one, and found that it works to stop getopt errors from listening to me with these errors. Basically, just make mistakes to oblivion.

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

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

+2
source share

All Articles