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
DEBUGtrap 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.
ERRtrap runs when any of the conditions triggering
errexitoccur (it doesn’t override
errexitthough, so the script will still exit at that point). This can be useful to print specific debugging information, for example:
trap 'echo "$counter"' ERR..
EXITtrap 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 run
exitat the end of the
RETURNtrap is similar to
EXIT. It runs when a function or sourced script (that is,
source FILE) finishes.
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.