1

Recently, I was wondering how you change the exit status or end status of a script in bash. For example; say we run test.sh and inside the program it exits using exit 0… I was wondering what would be a normal procedure to change this exit status to say 1? I know that you could use exit 1 but is this an actual standard of setting the exit status?

0

2 Answers 2

4

The exit status of a script is the exit status of the last command that was executed. For example if the last statement tries to create a directory with mkdir some/path, and the command fails, then the exit code of the script itself will be the exit code of the failed mkdir.

If you want to set a different exit code, you can, using the exit builtin:

exit: exit [n]
    Exit the shell with a status of N.  If N is omitted, the exit status
    is that of the last command executed.

If your script detects that something went wrong, then it's recommended that you exit with a non-zero code. Typically 1 is used, and it's good enough, until you want to give a different signal to caller programs in order to be able to respond to different kinds of errors differently. Unless you have a specific idea in mind, simply use exit 1.

0
1

Non-zero exit indicates an error. Zero indicates success. Trying to remove a file that doesn't exist, while a failure, is just as good in most cases as actually removing it so it is up to your script to decide whether such things should be treated as failure or success.

So what numbers should you use? In all my 30+ years using Unix, I never saw a standard. What's important for clarity if others are using your script is that you either use just a single exit code for failure or define what that exit code means. Definition can be included by many means. One way is to echo the exit code along with a list of possible causes to standard error as in

echo -e "Return code Error: " $Error "\n Possible errors are\n" \
"1 = missing parameter\n" \
"2 = Could not do what you wanted \n" >&2

Of course there are lots of alternatives like documenting errors in the code with comments (best to put it up front in script and not scattered throughout) or make an optional parameter to script as in

$myscript -error [other parameters if any]

which prints all the possible errors.

I have used error codes from scripts called by other scripts to be return info:

0 being success, Positive being error, Negative meaning no error but special action need be taken

That's not good if the called script is run directly as it may confuse the user but the called script can check for that condition.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .