Bash Safe Temporary Files
Safe temporary files are created with unique names and cleaned up. mktemp creates a name that no other process is already using.
A temporary directory is tested, used, then removed
The test proves the directory exists before use. The file inside it is printed, and the last line proves the directory is gone.
dir=$(mktemp -d)
if [ -d "$dir" ]; then echo "temp dir ready"; fi
printf "inside\n" > "$dir/note.txt"
cat "$dir/note.txt"
rm -rf "$dir"
if [ ! -d "$dir" ]; then echo "temp dir removed"; fiA temporary file is tested, used, then removed
The test proves the file exists before use. The file content is printed, and the last line proves the file is gone.
tmp=$(mktemp)
printf "work data\n" > "$tmp"
if [ -f "$tmp" ]; then echo "temp file ready"; fi
cat "$tmp"
rm "$tmp"
if [ ! -f "$tmp" ]; then echo "temp file removed"; fiA trap cleans up when a subshell ends
The subshell creates a temporary directory and traps its removal on exit. The parent then proves the directory is gone, without ever printing its path.
(
d=$(mktemp -d)
printf '%s' "$d" > saved-path.txt
trap 'rm -rf "$d"' EXIT
if [ -d "$d" ]; then echo "temp dir ready"; fi
)
saved=$(cat saved-path.txt)
if [ ! -d "$saved" ]; then echo "temp dir cleaned"; fi
rm saved-path.txtExample
dir=$(mktemp -d)
trap 'rm -rf "$dir"' EXIT
printf "result line\n" > "$dir/result.txt"
cat "$dir/result.txt"
echo "script finished"Key points
- mktemp: a command that creates a temporary file with a unique name.
- mktemp -d: the form that creates a temporary directory instead of a file.
- Test with [ -d ] for a directory and [ -f ] for a file, never by printing the path.
- trap ... EXIT: a cleanup command that runs when the script ends.
- Cleanup matters: a leftover temporary file can leak data or waste space.
- Remove with rm for a file and rm -rf for a directory made by mktemp -d.
In this example, mktemp -d creates a temporary directory and trap registers its removal for script exit. The script writes a result file inside the directory and prints it. The last line prints before the script ends, and the trap then removes the directory.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why use mktemp instead of a fixed temporary name?