Track BASH script command failures or abort after N failures
Using the trap
built-in signals received by a scripts (e.g. SIGINT
). Using this functionality a script can also take actions based on errors. This can allow some more nuanced handling as opposed to set -e
.
#!/bin/bash
ErrorThreshold=5
Cumulative_RC=0
ErrorCount=0
TrackErrorTrap() {
((Cumulative_RC += $?))
((ErrorCount++))
if [[ $ErrorCount -gt $ErrorThreshold ]]; then
echo -e "\n\n###############################"
echo "Too many errors"
echo "Count : $ErrorCount"
echo "Total RC: $Cumulative_RC"
exit $Cumulative_RC # Don't need to exit, can just take some action
fi
}
trap TrackErrorTrap ERR
for I in {1..10}; do
echo -n "Error #: $I "
false # when ErrorThreshold is exceeded, the trap will abort
echo "[COMPLETE]"
done
# script never makes it this far
echo "The rest of the script"
Running the above results in:
Error #: 1 [COMPLETE]
Error #: 2 [COMPLETE]
Error #: 3 [COMPLETE]
Error #: 4 [COMPLETE]
Error #: 5 [COMPLETE]
Error #: 6
###############################
Too many errors
Count : 6
Total RC: 6