What is the meaning of exit 0, exit 1, and exit 2 in a bash script?

Here's one good reference for shell exit codes:

Exit code 0        Success
Exit code 1        General errors, Miscellaneous errors, such as "divide by zero" and other impermissible operations
Exit code 2        Misuse of shell builtins (according to Bash documentation)        Example: empty_function() {}

Caveat: Using the proper exit code is not a requirement and is not enforced by the shell. Developers can ignore the guidance if they think it wise.


Using exit and a number is a handy way of signalling the outcome of your script. It mimics the way that bash commands output a return code. With bash commands the return code 0 usually means that everything executed successfully without errors. exit also makes your script stop execution at that point and return to the command line.

Any return code greater than 0 indicates an error of some sort, though sometimes the error isn't critical, for each command it should be possible to find some documentation that tells you what each return code means.

You can get the return code of the last bash command by using the shell variable $? like so:

$ echo "something"
something
$ echo $?
0
$ cp
cp: missing file operand
Try 'cp --help' for more information.
$ echo $?
1

When you use this in a script, you can query the return code in the same way when it's done executing. So you'll see that having:

exit 2
exit 0

Is sort of meaningless, as you can never reach the exit 0 part.


All by itself, exit implies an exit value of zero, or successful completion of your script. You do not have to add the zero argument to the exit command to indicate successful completion. Your script may (or probably will) exit successfully although it tests for an erroneous condition. In this case you specifically want it to exit with the error (or 1) condition.

echo -e "Enter numbers 1-4" \c"
read NUM
case $NUM in 
    1) echo "one";;
    2) echo "two";;
    3) echo "three";;
    4) echo "four";;
    *) echo "invalid answer"
       exit 1;;
esac

The exit command in the last line does not have to be there at all. It could be called with the zero or not called at all. Without specifying the 1 argument to the exit command the answer in all these cases to the echo $? would be zero.

However by specifying the 1 argument to the exit command the response to the echo $? would be 1. So use the 1 argument to the exit command when you want to specify that the script has exited with an error condition.

Tags:

Bash

Scripts