0
0
Bash Scriptingscripting~3 mins

Why trap for cleanup on exit in Bash Scripting? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your script could clean up its mess no matter how it ends?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
rm temp.txt
# but if script is stopped early, temp.txt stays
After
trap 'rm -f temp.txt' INT TERM EXIT
# temp.txt is removed automatically on any exit
What It Enables

You can write scripts that always clean up safely, making your system neat and your scripts reliable.

Real Life Example

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.

Key Takeaways

Manual cleanup is unreliable and error-prone.

trap runs cleanup code on script exit automatically.

This keeps your system clean and scripts dependable.