When parsing command line arguments with GNU
getopt command, how do I (if possible) do recognize
-? as another option? Is there a way to escape it in the opstring?
The man page getopt(3) states:
If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in
optopt, and returns
?. The calling program may prevent the error message by setting opterr to 0.
? is used to signal "unknown option" and cannot be used as
an option value. (It would be impossible to tell the option
an unknown option.)
Even if you could recognize that as an option string, it would be a really bad idea to use the question mark character as a real argument because most shells use this as part of their glob syntax (representing that the character before it is optionally use or not in the match). Passing a litteral
? would be difficult for users because they would have to escape it.
If you are creating a help option of some kind the usual syntax is to look for short and long options of
To get the effect of using the question mark for help, try simply checking to see if the unknown option is indead the question mark character.
For example, I want to print out a message "Unknown option" whenever the unknown option is NOT the question mark. Next I always call my usage function.
\?) if [ "$OPTARG" != "?" ] ; then echo "Unknown option \"$OPTARG\"" ; fi usage
In general, I would agree and use the
h option for help and the
u option for
usage, but I had already used those for
user and I liked it that way.
PS. I'm using bash on Solaris 10.