Make your scripts clean up after themselves, even when they crash

Shell Scripting / Bash Tricks

Make your scripts clean up after themselves, even when they crash

🧩 The Challenge

Ever had a script create temporary files, lock files, or start background processes, and then just *die* without cleaning up? You’re left with junk cluttering up /tmp, lingering PIDs blocking new runs, or worse, half-finished data. It’s a mess, and trying to debug why things aren’t starting cleanly after a crash can eat up your whole morning. Nobody tells you how to handle this gracefully when you’re just starting out.

💡 The Fix

You need a way to tell your script, “Hey, no matter how you exit, run *this* command first.” That’s where `trap` comes in. It lets you define cleanup actions that fire when your script receives common termination signals or even just exits normally. It’s a lifesaver for making scripts robust and preventing clutter.

trap "rm -f /tmp/my_script.lock.$$; kill \$(jobs -p); echo 'Cleanup complete!'" EXIT INT TERM

⚙️ Why It Works

This command tells Bash to execute the specified string whenever the script receives an `EXIT` signal (normal termination), `INT` (Ctrl+C), or `TERM` (kill command). Using `$$` (the current process ID) makes your temporary files unique. And `kill $(jobs -p)` is a handy trick to terminate any background processes started by the script.

🚀 Pro-Tip: Put your cleanup logic in a separate function, then just `trap my_cleanup_function EXIT INT TERM`. Much cleaner!

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted