Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should bash scripts called with --help argument return 0 or not-zero exit code? [closed]

Tags:

bash

exit-code

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?

  • Tools like: grep (on MacOS), man return a non-zero exit code.
  • Tools like: bash, sh, vim return 0 as exit code.
like image 212
4 revs, 2 users 76% Avatar asked Jun 14 '26 19:06

4 revs, 2 users 76%


1 Answers

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.)

like image 116
PSkocik Avatar answered Jun 17 '26 10:06

PSkocik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!