Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps