Site icon New Generation Enterprise Linux

Stop leaving temp files all over the place

Shell Scripting / Bash Tricks

Stop leaving temp files all over the place

🧩 The Challenge

Ever have a script bomb out and leave some junk files in `/tmp` or even worse, your current directory? You clean them up, run it again, and now some other script has clobbered your `tmp.txt` because you both picked the same name. It’s a pain to debug, and a security nightmare if those files contain sensitive stuff.

💡 The Fix

Just use `mktemp`. It makes unique, secure temporary files and directories, and you can tell it to clean up after itself when your script exits. No more race conditions, no more leftover garbage.

#!/bin/bash
set -euo pipefail

# Create a temporary directory that gets cleaned up on exit
TMP_DIR=$(mktemp -d -t myapp.XXXXXX)
trap 'rm -rf "$TMP_DIR"' EXIT

# Create a temporary file inside that directory
TMP_FILE=$(mktemp "$TMP_DIR/config.XXXXXX")

# Now use them
echo "This is important config data" > "$TMP_FILE"
echo "My temporary directory is: $TMP_DIR"
echo "My temporary config file is: $TMP_FILE"

# Simulate some work or error
# sleep 2
# exit 1 # uncomment to see cleanup on error

# The trap will clean up $TMP_DIR and $TMP_FILE automatically on script exit.

⚙️ Why It Works

`mktemp` creates files or directories with a unique suffix, preventing name collisions. The `trap ‘rm -rf “$TMP_DIR”‘ EXIT` part is magic; it tells bash to run that `rm` command whenever the script exits, whether it succeeds or fails.

🚀 Pro-Tip: Always `set -euo pipefail` in your scripts. It’s like wearing a seatbelt.

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

0 0 votes
Article Rating
Exit mobile version