How to Handle Signals and Errors in Bash Scripts
A trap is a signal handler specified in Bash. To set up a trap for any number of signals, use trap COMMAND SIGNAL…
. Whenever the script receives any of these signals it will execute the command. trap
supports some important pseudo–signals (that is, they can be trapped but are not “real” signals, so we can’t send them with kill
):
The
DEBUG
trap runs before every command. We can use it to print useful context such as the value of a variable or even to step through each line:trap 'read -p "$BASH_COMMAND"' DEBUG
.The
ERR
trap runs when any of the conditions triggeringerrexit
occur (it doesn’t overrideerrexit
though, so the script will still exit at that point). This can be useful to print specific debugging information, for example:trap 'echo "$counter"' ERR
..The
EXIT
trap runs when a script is exiting. This is really helpful to do the kind of cleanup which should happen after the script has nothing else left to do, such as removing any temporary directories. This trap does not interrupt the termination of the script, so there is no need to runexit
at the end of theEXIT
trap code.The
RETURN
trap is similar toEXIT
. It runs when a function or sourced script (that is,. FILE
orsource FILE
) finishes.
For example:
xxxxxxxxxx
trap 'echo "Continuing…" >&2' CONT
while true
do
sleep 0.001
done
When this script starts it sets up the traps and sleeps repeatedly unless interrupted. Let’s explore how this works. Run the script, then press Ctrl–z to pause it, and then resume the script in the foreground by running fg
. At this point the script should print “Continuing…”. Press Ctrl–c to terminate the script.
This lesson preview is part of the The newline Guide to Bash Scripting course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to The newline Guide to Bash Scripting, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
