Bash : automatically exit the script if a command fails

Use the command set -e for testing the return code.

"set -e, an alias of set -o errexit, is used to exit the script everytime a command fails. By putting this command at the top of your script, you can avoid to manually test all the return codes.

Automatically test if a command fails

#!/bin/bash # Exit for a return code not 0 set -e; true; # Do not exit for a return code not 0 # until the next set -e set +e; false; echo 'This false does not exit the script'; false; if [ $? -ne 0 ]; then echo 'That\'s how we can manually check that the return code is not 0'; fi # Put back the automatic exit set -e; false || { echo "Custom error message"; } echo 'Still in the script because the return code of false || echo ... is 0'; false; echo 'Will never be displayed because the previous command exited the script';

Result of this script

$ ./script.sh This false does not exit the script That's how we can manually check that the return code is not 0 Custom error message Still in the script because the return code of false || echo ... is 0

Another use of set for testing if a variable is initialized.