Create safe temporary files with mktemp

Replace predictable /tmp filenames with collision-proof, permission-safe temp paths in scripts.

LinuxbashFilesscriptstemp-filesLow risk
Use tmpfile=$(mktemp) for a file, tmpdir=$(mktemp -d /tmp/backup-XXXXXX) for a directory, and clean up with a trap 'rm -rf "$tmpdir"' EXIT.

01Command

Command
$ tmpdir=$(mktemp -d /tmp/backup-XXXXXX) && echo "$tmpdir"

02What it does

Hand-built names like /tmp/$$.log are predictable and race-prone: an attacker can pre-create the path and hijack your writes. mktemp creates the file atomically with mode 0600 and prints the unique name, so only your script can touch it. The template's trailing XXXXX block becomes a random suffix, and mktemp -d makes a whole scratch directory.

03Risk

RiskLow risk
Requirementsmktemp is part of GNU coreutils; available on every Linux distro.
!Warning: mktemp only creates the path — delete it yourself on exit, typically via trap. The file mode is 0600 for files but a mktemp -d directory is 0700; files you create inside it keep your umask, so secrets still need chmod 600.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

  • mktemp(1) - Linux manual page
    man7.org · community · 2026-09-17
    Evidence: mktemp [OPTION]... [TEMPLATE] creates a temporary file or directory; TEMPLATE must contain at least 3 consecutive Xs and -d/--directory is documented.
  • mktemp(1) — Debian bookworm
    Debian Manpages · community · 2026-09-17
    Evidence: Documents the TEMPLATE requirement (at least 3 X's in the last component), --suffix and the safe creation mode 0600.

Last verified: 2026-09-19 · Category: Files & Folders

06Related solutions