Optional option argument with getopts

Wrong. Actually getopts does support optional arguments! From the bash man page:

If  a  required  argument is not found, and getopts is not silent, 
a question mark (?) is placed in name, OPTARG is unset, and a diagnostic
message is printed.  If getopts is silent, then a colon (:) is placed in name 
and OPTARG is set to the option character found.

When the man page says “silent” it means silent error reporting. To enable it, the first character of optstring needs to be a colon:

while getopts ":hd:R:" arg; do
    # ...rest of iverson's loop should work as posted 
done

Since Bash’s getopt does not recognize -- to end the options list, it may not work when -R is the last option, followed by some path argument.

P.S.: Traditionally, getopt.c uses two colons (::) to specify an optional argument. However, the version used by Bash doesn’t.

Leave a Comment