Tidy up after your shell scripts every time

Shell Scripting / Bash Tricks

Tidy up after your shell scripts every time

🧩 The Challenge

Ever write a script that needs a temporary file or directory? Of course you have. And if you’re like me, you probably just picked `/tmp/myscript-stuff` and hoped for the best. But that leaves junk behind, or worse, someone else’s script stomps on your files.

💡 The Fix

There’s a super robust way to create temporary files and directories that get unique names and clean themselves up automatically, even if your script crashes. This means no more `/tmp` pollution and no more race conditions.

#!/bin/bash
set -euo pipefail

# Create unique temporary directory and file
TEMP_DIR=$(mktemp -d -t myapp.XXXXXX)
TEMP_FILE=$(mktemp -t myapp.XXXXXX)

# Ensure everything gets cleaned up on exit, no matter what.
# I've wasted hours cleaning up /tmp cruft because I forgot this.
trap 'rm -rf "$TEMP_DIR" "$TEMP_FILE"' EXIT

echo "Temp dir created: $TEMP_DIR"
echo "Temp file created: $TEMP_FILE"

# Now do your script's work using these paths
echo "This is some sensitive info." > "$TEMP_FILE"
cp /var/log/syslog "$TEMP_DIR/recent_logs.log" 2>/dev/null || echo "No syslog for you."
ls -l "$TEMP_DIR"
cat "$TEMP_FILE"

# Script finishes, the trap fires, everything's gone.
# If the script errors out halfway, still gone. It's beautiful.
sleep 1

⚙️ Why It Works

`mktemp` gives you a unique, non-existent file or directory path. And that `trap` command? That’s the magic. It tells Bash to run `rm -rf` on your temp paths right before the script exits, whether it’s a normal exit or an unexpected error.

🚀 Pro-Tip: Use `myapp.XXXXXX` with `mktemp` to add a prefix for easier identification in `ls /tmp`, but still keep it unique.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted