Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit Code when called with No Arguments

Tags:

bash

exit-code

I have a script that requires at least one argument. If the arguments are incorrect I will obviously return a non-zero exit code.

I have decided to print the usage instructions when called with no arguments, but I'm uncertain of the exit code. Should it be

  • 0 (success)
  • one of the values [1-125] (error)

An argument could be made either way. Is some option recommended?

like image 579
Eero Aaltonen Avatar asked Oct 19 '25 14:10

Eero Aaltonen


2 Answers

It depends on whether you want the callers of your script to know programatically why it failed.

If, for example, it will only ever be run by a human, you could just return 1 and rely on the error text to inform them.

You could even return zero regardless if you only ever want a human to easily know (via the output) if it failed but I would consider this very bad form - Microsoft have made this mistake in the past with some of their commands not setting %errorlevel%, making it very difficult for a script to figure out whether it's worked or not.

Even if you decide not to indicate why it failed, you should at least indicate that it failed.

If you want a program to easily figure out why it failed, return a different code for each discernible error type.

like image 122
paxdiablo Avatar answered Oct 22 '25 06:10

paxdiablo


Any Unix command when it returns control to its parent process returns a code, number between 0 and 255.

Success is traditionally represented with exit 0; failure is normally indicated with a non-zero exit-code. This value can indicate different reasons for failure.

So what you have also is another case of unsuccessful completion of your program which should be treated as returning a proper error code and not 0.

Also note that traditional Unix system calls don't signal an error code for empty arguments, they have to be caught explicitly. There are ones for argument list too long (E2BIG) and invalid arguments (EINVAL).

like image 44
Inian Avatar answered Oct 22 '25 06:10

Inian