This week in Bash Scripting Sunday, we’re diving into a small topic with a big impact: handling temporary files safely and securely.
Temporary files are common in scripting — for holding intermediate data, logs, or scratch work. But if you’re using something like:
tmpfile="/tmp/myscript.tmp"
…you might be exposing yourself to race conditions, file collisions, or even security issues.
Let’s fix that. 🛠️
🧪 The Problem with Hardcoded Temp Files
Hardcoding paths like /tmp/foo.txt
can lead to problems:
- If two users/scripts run at once, they’ll overwrite each other’s data
- It can leak sensitive information
- It’s predictable, so it might be exploited by a malicious user
Instead, use tools designed for safe, atomic temporary file creation.
✅ The Solution: mktemp
mktemp
is your friend for securely creating temporary files or directories.
tmpfile=$(mktemp)
echo "Working in $tmpfile"
This guarantees a unique file path like:
/tmp/tmp.zsY9Xc2S0b
Want a custom prefix?
tmpfile=$(mktemp /tmp/myscript.XXXXXX)
Use XXXXXX
to mark where randomness should go.
🧽 Cleaning Up: trap
to the Rescue
A good script is a tidy script. Use trap
to clean up your temp file automatically, even if your script exits early.
tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT
Now, when the script exits (normally or due to an error), the temp file is gone.
🧪 Example: Sorting a Large File Without Modifying the Original
#!/usr/bin/env bash
input_file="$1"
[ -f "$input_file" ] || { echo "File not found"; exit 1; }
sorted_tmp=$(mktemp)
trap 'rm -f "$sorted_tmp"' EXIT
sort "$input_file" > "$sorted_tmp"
# Do something with the sorted data
head "$sorted_tmp"
This ensures the original file remains untouched, and cleanup happens automatically.
📁 Temporary Directories Too!
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
Now you’ve got a whole isolated workspace that cleans itself up.
🚫 Common Pitfalls
- ❌ Don’t use predictable filenames in
/tmp
- ❌ Don’t forget to clean up — use
trap
- ✅ Always quote variable expansions:
"$tmpfile"
🧵 Summary
- Use
mktemp
to safely create temp files/dirs - Set traps to clean up automatically
- Avoid fixed names and race conditions
Next week, we’ll explore logging techniques — from simple echo
lines to syslog integration.
Happy scripting! 🐚