What if your script could clean up its mess no matter how it ends?
Why trap for cleanup on exit in Bash Scripting? - Purpose & Use Cases
Imagine you run a script that creates temporary files or starts background tasks. If you stop the script suddenly or it crashes, those files or tasks stay behind, cluttering your system.
Manually cleaning up after every possible exit is hard. You might forget some cases, or the script might be interrupted unexpectedly. This leads to leftover files, wasted space, or stuck processes.
The trap command lets your script catch exit signals and run cleanup code automatically. This means no matter how the script ends, it tidies up after itself.
rm temp.txt
# but if script is stopped early, temp.txt staystrap 'rm -f temp.txt' INT TERM EXIT # temp.txt is removed automatically on any exit
You can write scripts that always clean up safely, making your system neat and your scripts reliable.
A backup script creates a temp folder to store files. Using trap, it deletes the folder even if you press Ctrl+C to stop it.
Manual cleanup is unreliable and error-prone.
trap runs cleanup code on script exit automatically.
This keeps your system clean and scripts dependable.