Juicy lil' bytes

How to Test for the Success of a Previous Command in a Bash Shell Script

This bash idiom captures the exit status code from the previous command that was executed. You can use it to confirm that the last command was successful in your shell script.

Exit Status Code

Description Idiom
Exit Status Idiom$?

Use Example

Here is an example of how you could use it to confirm that a command was executed successfully:

1
2
3
4
5
6
7
8
9
10
# run git pull and test for exit code = 1 = failure
git pull
if (( $? )); then
  echo "Failure" >&2
  exit 1
else
  echo "Success"
  # code block that is dependent on success of previous command
fi
exit 0