简体   繁体   中英

getopt returns 0 exit status for unrecognized option

The Unix man page for getopt states

If there are problems parsing the parameters, for example because a required argument is not found or an option is not recognized, an error will be reported on stderr, there will be no output for the offending element, and a non-zero error status is returned.

However, in my shell (GNU Bash 5.2.15):

$ getopt --long foo -- --bar
 --
$ echo $?
0

In other words, getopt returned 0 (success) even though it was given an unrecognized option "--bar". Shouldn't getopt return a non-zero exit status in this case?

In that invocation, getopt was not given an unrecognised option. It was not given any option, because --bar , being the first parameter, was interpreted as an optstring, as indicated in man 1 getopt :

If no -o or --options option is found in the first part, the first parameter of the second part is used as the short options string.

After that, there were no parameters left, which is perfectly legal.

I know that this doesn't seem entirely consistent with the description of the -o option to getopt , but that description is internally inconsistent, since it clearly indicates that an optstring can start with a - (meaning that getopt should emit non-option parameters immediately, which makes it a lot harder to interpret the return value). I believe that what was meant was "the first parameter of getopt in the first part of the command line ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM