Detecting command failures in bash
Suppose you want to detect weather all the commands executed successfully in your script:
#!/usr/bin/env bash
# make sure the script exits as soon
# as first error is encountered
set -e
success=0
# call our function on (nice) exit of the script
trap on_exit 0
on_exit(){
if (( success )); then
echo 'all commands executed successfully'
else
echo 'at least one command failed'
fi
}
# your commands go here
true
#false
# if the execution come to here means
# set -e did NOT exit the script
success=1
Some notes:
- Uncomment "false" to see the code work
- set -e depends on the commands behaving nicely and returning a non zero exit code on error. Just about all standard tools do this.
- The on_exit will NOT be called if your script was interrupted with SIGKILL
- Dummy echo commands are useless :), you should replace them with something like mailing/logging
