Linux commands
Browse topics

Creating temporary files and directories with mktemp

Version
unversioned
Review
Draft

Summary#

mktemp creates an empty file and prints its path. Add -d to create a directory. The initial permissions are private to your user, subject to your umask.

Syntax#

sh
mktemp -- /tmp/report.XXXXXXXX
mktemp -d -- /tmp/report-work.XXXXXXXX

The trailing X characters are replaced to form a unique name. A GNU template needs at least three consecutive X characters in its final component. Capture the printed path with $(...), check that creation succeeded and double-quote the variable each time you use it.

Example#

The script creates a private workspace and a temporary report under a path containing a space. The EXIT trap removes the workspace on normal exit or if a command fails under set -e. The random paths vary, so the script prints the report content.

sh
(
  set -eu
  work=$(mktemp -d /tmp/devlookup-mktemp.XXXXXXXX)
  trap 'rm -rf -- "$work"' EXIT

  parent="$work/staged files"
  mkdir -- "$parent"
  report=$(mktemp -- "$parent/report.XXXXXXXX")
  printf '%s\n' 'rows=3' > "$report"
  printf 'saved: '
  cat -- "$report"
)

Expected output#

Text
saved: rows=3

Common mistakes#

Avoid mktemp -u for paths you intend to write to. It prints a possible name without reserving it, so another process can create that path before your script opens it. Names based on $$ are predictable and have a similar race. Register cleanup after successful creation and keep recursive deletion scoped to the quoted directory you just created.

Version applicability#

GNU coreutils added mktemp in the 6.9.90 beta and shipped it in stable 6.10. The example uses explicit templates and a shell that supports an EXIT trap. It was verified with GNU coreutils 9.7 and uutils coreutils 0.10.0.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0