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?
The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately. getopt allows for the parsing of long options ( --help instead of -h ); getopts does not.
Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.
On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script.
OPTARG. Stores the value of the option argument found by getopts. OPTIND. Contains the index of the next argument to be processed.
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
;;
esac
done
./innerscript $*
$ ./blah.sh -s 20140503 -i 3 -a -b -c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With