🐧 Linux / Shell Scripting
Intermediate
How does trap work for signal handling in bash?
Answer
trap registers a command or function to be executed when the shell receives a specified signal or exits. Common patterns: trap "cleanup; exit" INT TERM runs cleanup when the script is interrupted (Ctrl+C) or terminated. trap cleanup EXIT runs cleanup on any exit — normal, error, or signal — making it the bash equivalent of a finally block. This is essential for scripts that create temporary files or acquire locks: TMPFILE=$(mktemp); trap "rm -f $TMPFILE" EXIT ensures the temp file is deleted no matter how the script ends. trap "" SIGINT ignores a signal. List current traps with trap -l.
Previous
What is $? and how does exit status error handling work in bash?
Next
How do arrays work in bash?