What is `trap`, and what are the common signals and pseudo-signals?
BeginnerConceptFunctions, exit codes, strict mode and traps
Answer
trap 'commands' SIGNAL... runs commands when the shell receives a signal or hits a pseudo-signal.
| Name | When |
|---|---|
EXIT |
shell exits for any reason (normal, exit, error under -e, handled signal) |
ERR |
a command fails (same rules as set -e) |
INT |
Ctrl+C (SIGINT) |
TERM |
kill, systemctl stop, docker stop, Kubernetes pod termination |
HUP |
terminal closed; daemons use it for "reload config" |
DEBUG / RETURN |
before each command / after a function returns |
SIGKILL and SIGSTOP cannot be trapped. trap -p lists traps; trap - EXIT removes one.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner