shell programming - trapping signals

created onJanuary 18, 2022

general usage of trap

trap signals that are sent to the shell script:

trap '<some code>' <signal 1> [ <signal 2>, <signal 3>, ... ]

where is the signal (or signals) to trap and is the code to execute when a signal is trapped. can span multiple lines:

trap <code that spans several lines>' <signal> [ <signal 2>, <signal 3>, ... ]

can be any signal that can be sent to a process. For a complete list of all signals, use . Two special signals are available:

  • ERR this signal is received by trap, whenever $? is not equal to 0 (zero)
  • EXIT this signal is received by trap, whenever a scripts exits. This is great for cleanup before a script exits

signals that can’t be trapped

SIGKILL and SIGSTOP can’t be trapped or ignored by any process.

restoring defaults for signals

the default action for a signal is restored with

scope of traps

trapping signals and restoring defaults of signals can be used to define the scope of traps.

the scope of a trap of a signal is from the position of the trap definition to the end of the script file or the restoring of the defaults for the signal.

in the following example, is executed, whenever in code block B a value not equal to 0 (zero) is assigned to , but not in code block A or code block C:

someFunction () { ... } <code block A> trap 'someFunction' ERR <code block B> trap - ERR <code block C>

key combinations for signals

if the script is running in the foreground in the current shell, signals can be send to the script with a key combination.

signal key combination
INT CTRL-C
QUIT CTRL-\
TSTP CTRL-Z
STOP CTRL-S
CONT CTRL-Q

clean up on exit with trap

for clean up on exit of a script, the code executed by trap must include . otherwise the script does not exit.

trap 'rm -f /tmp/whatEver; exit 0' EXIT