Stop wasting time cleaning up your bash temporary files

Shell Scripting / Bash Tricks

Stop wasting time cleaning up your bash temporary files

🧩 The Challenge

You know that feeling when your /tmp directory is littered with hundreds of abandoned files because a script crashed halfway through? It is honestly embarrassing how many times I have had to manually scrub those things when the disk starts throwing warnings.

💡 The Fix

Use a trap command to ensure your script cleans up its own mess before it exits, whether it finishes successfully or blows up. This keeps your server clean and saves you from those awkward conversations with storage monitoring tools.

cleanup() { rm -f "$tmp_file"; }
trap cleanup EXIT
tmp_file=$(mktemp /tmp/my-script.XXXXXX)

⚙️ Why It Works

Adding the EXIT signal to your trap makes sure the cleanup function runs regardless of how the script terminates. It catches everything from natural exits to those annoying moments when you hit ctrl-c during a debug session.

🚀 Pro-Tip: Always use mktemp instead of hardcoding filenames to avoid collisions when multiple instances run at once.

Linux Tips & Tricks | © ngelinux.com | 9/1/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted