Writing a bash script that displays the usage information when called with --help
argument, what exit code is it recommended to return/exit the script with?
$ my_script --help; echo $?
Usage ...
0
or
$ my_script --help; echo $?
Usage ...
1
If there are different opinions, what are the arguments for one or the other options?
grep
(on MacOS), man
return a non-zero exit code.bash
, sh
, vim
return 0 as exit code.The output should go to stdout
and the script should return 0 unless there was an IO error. (The user requested a help screen and you delivered. The operation was a success.)
If you output the same help screen as a response to incorrect use, output it to stderr
and fail (=exit with a nonzero).
(The user tried to do something but they did it wrong — the operation failed and you're giving them a hint via stderr
(because on stdout
, they might well be expecting something else) as to how they might do it right.)
I think these are good and reasonable practices, and most good CLI tools I've seen follow them.
(This includes my Linux Mint's grep
, man
, and ping
, with the caveat that ping
complains of not having a help option, but it does so consistently with the 2nd paragraph of this advice.)