Create safe temporary files with mktemp
Replace predictable /tmp filenames with collision-proof, permission-safe temp paths in scripts.
01Command
$ 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
04Undo
✓No undo needed — this command does not change persistent state.
05Sources
- mktemp(1) - Linux manual pageEvidence: 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 bookwormEvidence: 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
Find every occurrence of a pattern across all files in a tree, printed as file:line:number matches.
Unpack a gzipped tarball into the current directory while printing each file as it is extracted.
Show total, used, and available space plus usage percentage for every mounted filesystem in human-readable units.