Don’t leave a mess when your script bombs out

Shell Scripting / Bash Tricks

Don’t leave a mess when your script bombs out

🧩 The Challenge

Ever had a shell script create a bunch of temporary directories or files, then you hit Ctrl+C because something went sideways? And suddenly you’ve got orphaned `/tmp/my_script_xyz/` directories hanging around, or maybe a lock file nobody cleaned up? Nobody tells you early on that scripts *will* die unexpectedly, and you’re left to sweep up the mess manually.

💡 The Fix

There’s a simple Bash feature that lets your script reliably clean up after itself, even if it gets interrupted or crashes. It’s called `trap`, and it’s a lifesaver for making your scripts robust. You just tell the shell what command to run right before the script exits, no matter how it exits.

#!/bin/bash
TEMP_DIR=$(mktemp -d)
trap 'echo "Cleaning up $TEMP_DIR"; rm -rf "$TEMP_DIR"' EXIT INT TERM
echo "Created temp dir: $TEMP_DIR"
touch "$TEMP_DIR/foo" "$TEMP_DIR/bar"
echo "Sleeping for 10s. Hit Ctrl+C to test cleanup."
sleep 10
echo "Script finished."

⚙️ Why It Works

The `trap` command registers a cleanup routine (in this case, `rm -rf “$TEMP_DIR”`) to execute when the script receives certain signals. `EXIT` means it runs on a normal exit, `INT` is for Ctrl+C, `TERM` for a `kill` command. This ensures your temporary files are gone, no matter what.

🚀 Pro-Tip: Use `mktemp -d` to create unique temporary directories, then let `trap` handle the deletion.

Linux Tips & Tricks | © ngelinux.com | 10/31/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted