trap
trap is like setting a safety net that goes off when something surprising happens, such as someone pressing Ctrl+C, so your script can tidy up before it leaves.
In this page:
Syntax
trap 'commands_or_function' SIGNAL
trap
trap registers a command or function to run when the script receives a specific signal, like SIGINT (Ctrl+C) or EXIT (whenever the script ends, for any reason).
trap cleanup EXIT is a common pattern to guarantee cleanup code always runs. Traps are essential for writing scripts that clean up temp files or background jobs reliably.
Note:
trap cmd EXIT runs on every exit path — normal completion, an error, or a signal — making it ideal for guaranteed cleanup.Example: trap
#!/bin/bash
cleanup() {
echo "Cleaning up before exit..."
}
trap cleanup EXIT
echo "Doing some work..."
echo "Script is about to finish"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trapping signals that cannot be caught, such as
SIGKILL. - Forgetting to quote the trap command, so it expands too early.
- Not exiting inside a trap for
SIGINT, so the script continues after Ctrl+C.
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: