trap builtin
The builtin that runs a command or function when the shell receives a signal or exits, used for cleanup.
In more detail
trap cleanup EXIT runs cleanup however the script ends, and adding INT and TERM covers Control C and kill. trap with no arguments lists the handlers and trap - EXIT removes one. SIGKILL cannot be trapped, so no handler runs when a process is killed that way.
Example
trap cleanup EXIT INT TERMRelated terms
- EXIT trap — A trap on the special name EXIT, whose handler runs whenever the shell exits: at the end, on exit, or when set -e stops it.
- signal — A short notification the kernel delivers to a process, such as please stop or stop now.
- SIGINT — The interrupt signal, sent to the foreground program when you press Control C, asking it to stop.
- SIGTERM — The signal that politely asks a process to finish its work and exit.
- mktemp — The command that safely creates a new, uniquely named temporary file, or with -d a directory, and prints its path.
Taught in
- Which Shell Am I In, And Getting Bash Five — Bash Scripting & Command Line Automation
- Single Quotes, Double Quotes, Backslash — Bash Scripting & Command Line Automation
- Finding Lines: grep And Regular Expressions — Bash Scripting & Command Line Automation
- Command Substitution And Subshells — Bash Scripting & Command Line Automation
- set -e, set -u And pipefail: Promises And Traps — Bash Scripting & Command Line Automation
- trap, Cleanup And Temporary Files — Bash Scripting & Command Line Automation
- Debugging: set -x, bash -n And Reading The Error — Bash Scripting & Command Line Automation
- Processes, Jobs And Signals — Bash Scripting & Command Line Automation
- Scheduling, Monitoring And A Script That Reports — Bash Scripting & Command Line Automation