Create unique, race-free temporary files and directories for scripts and tools. 16.11.2025 | reading time: 2 min When he needs a safe temporary file, he uses mktemp to avoid name collisions and races; mktemp creates unique file names and can create directories too. Quick demo Try mktemp interactively to see what it does ``` $ mktemp /tmp/tmp.K7a8x3 $ mktemp -d /tmp/tmp.gM4Y2b $ mktemp /tmp/myjob.XXXXXX /tmp/myjob.b4T9sQ ``` Use it inside a script Create and clean up a temp file automatically with trap ``` #!/bin/sh TMPFILE="$(mktemp /tmp/myjob.XXXXXX)" trap 'rm -f "$TMPFILE"' EXIT echo "Working" > "$TMPFILE" cat "$TMPFILE" ``` Options and pitfalls Remember the common options: -d makes a directory, -p chooses a directory, --suffix adds an extension, and supplying a template with at least six X characters controls the name; avoid -u because it prints a name without creating it and opens a race condition, and test behavior on different Unix variants because BSD and GNU implementations differ. When security matters mktemp uses atomic creation so it is safer than ad hoc names; still, prefer mkstemp in C programs or high-security contexts, check mktemp exit codes, and always arrange deterministic cleanup with trap or systemd/tmpfiles when scripts can be interrupted. Related utilities to consider Use the language-native tempfile APIs when available, consider systemd-tmpfiles for managed temp directories, and remember distribution-specific helpers for temporary data in service units. Next steps Start replacing fragile temp-name hacks with mktemp in your scripts, then explore language libraries and system services for more complete solutions; to deepen your Linux skills consider studying for certificates like CompTIA Linux+ or LPIC-1 and try intensive exam preparation at bitsandbytes.academy. Join Bits & Bytes Academy First class LINUX exam preparation. utilities scripting filesystem security