mktemp on Linux: Create Secure Temporary Files and Directories

mktemp command linux - custom-mktemp-featured.png

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"
mktemp
file

Random directory

mktemp -d for unpack staging or MySQL dumps.

bashdir
dir=$(mktemp -d)
echo "staging: $dir"
mktemp -d
dir

Custom template

Use XXXXXX where randomness is required in the pattern.

bashtemplate
mktemp --tmpdir backup.XXXXXXXX
template
XXXXXX

Cleanup trap

Remove temp paths on EXIT even when script fails.

bashtrap
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
# ... work in $tmpdir ...
trap
EXIT

Quick Reference

  • File: tmp=$(mktemp)
  • Dir: mktemp -d
  • Always trap cleanup

Related tutorials

Diagrams are original illustrations by Gnome IT Solutions. Tutorial text © Gnome IT Solutions.