trap
In this page:
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
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: