mktemp on Linux prevents symlink races and name collisions in /tmp — a common search when auditors flag shell scripts that write predictable paths like /tmp/mine.log.
See: tee,
/tmp cleanup,
cron wrapper.
Random file
Default template creates a file under /tmp with unique suffix.
bashfile
tmp=$(mktemp)
echo "data" > "$tmp"
ls -l "$tmp"

Random directory
mktemp -d for unpack staging or MySQL dumps.
bashdir
dir=$(mktemp -d)
echo "staging: $dir"

Custom template
Use XXXXXX where randomness is required in the pattern.
bashtemplate
mktemp --tmpdir backup.XXXXXXXX

Cleanup trap
Remove temp paths on EXIT even when script fails.
bashtrap
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
# ... work in $tmpdir ...

Quick Reference
- File:
tmp=$(mktemp) - Dir:
mktemp -d - Always
trapcleanup
Related tutorials
Diagrams are original illustrations by Gnome IT Solutions. Tutorial text © Gnome IT Solutions.