Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

The GNU getopt command uses the GNU getopt() library function to do the parsing of the arguments and options.

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.

Therefore ? is used to signal "unknown option" and cannot be used as an option value. (It would be impossible to tell the option -? from an unknown option.)

share|improve this answer
    
At the C level, you can find out if the ? was real by checking the original string. But apparently GNU getopt(1) just eats up the -? and returns 1. getopts is less confused (except, oddly, in ATT ksh), but doesn't expose the index of the character in the $OPTINDth parameter, which means you have to redo a lot of the work if you get a parameter like -a?b. –  Gilles Jun 28 '11 at 12:36

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 -h and --help.

share|improve this answer
2  
If you're using GNU getopt, you should support --help. –  cjm Jun 28 '11 at 10:36
1  
Actually, most of the time, -? wouldn't match anything and so would be passed literally to the command. But that's fragile (fails if you do have a file called -a, or under csh or zsh configured to complain on non-matching globs). –  Gilles Jun 28 '11 at 12:37
    
@cjm: yes. I already do. –  mschonaker Jun 28 '11 at 16:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.