Handling signals#

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 triggering errexit occur (it doesn’t override errexit 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 run exit at the end of the EXIT trap code.

  • The RETURN trap is similar to EXIT. It runs when a function or sourced script (that is, . FILE or source FILE) finishes.

For example:

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 page is a preview of The newline Guide to Bash Scripting

No discussions yet