Check the exit status of a previous command.

Check exit status value with if statement

This is a multi-line if statement, which is useful for more complex statements or if readability is important.

false

if [[ "$?" -eq 0 ]]; then
  echo 'Passed!'
else
  echo 'Failed!'
  exit 1
fi

Show message on failure only:

false

if [[ "$?" -ne 0 ]]; then
  echo 'Failed!';
  exit 1
fi

Check exit status of command directly

An if statement is used. But we don’t check $? but rather the command directly.

Here we check if packages are up to date (code 0) or outdated (code 1).

if npm outdated > /dev/null; then
  echo 'Nothing to update'
  exit 0
fi

echo 'Upgrading'
npm update

One-liner status check

Check if the status of the previous command was a pass or fail. This can help if the command is long and you don’t want to fit it on one line.

Skip error

This will keep going and not abort the script.

$ [[ $? -eq 0 ]] && echo 'Passed!' || echo 'Failed!'

Example use:

  • Use the true commands to give a zero (pass) exit status.
    $ true
    $ [[ $? -eq 0 ]] && echo 'Passed!' || echo 'Failed!'
    Passed!
    
  • Use the false commands to give a non-zero (fail) exit status.
      $ false
      $ [[ $? -eq 0 ]] && echo 'Passed!' || echo 'Failed!'
      Failed!
    

Exit on error

Note brackets are needed.

$ false
$ [[ $? -eq 0 ]] && echo 'Passed!' || (echo 'Failed!'; exit 1)