Last Updated: August 15, 2019
·
591
· buddylindsey

Error/Exit Code Checks in Bash

In your long bash scripts running many dependent tasks it is a good idea to verify each task completed properly. That is why you should check the exit code of the previously executed command. You can do that using $?. It returns the integer of your exit code.

The following will echo the number to the command line

prompt$ echo $?

Exit Codes

If you get a non-zero response something went wrong. Exit codes have no inherit meaning other than what you assign them in your documentation.

0 is Success<br />
>0 is Error

Example

An example piece of code to check for errors in your code would be:

if [ $? -ne 0 ]; then
  exit 1
fi

This exits your bash script with an error code thrown if the previous command executed fails as well.