Skip to content
Latchkey

mktemp: Usage, Options & Common CI Errors

mktemp creates a uniquely named temp file or directory and prints its path.

mktemp is the safe way to make scratch space - no predictable names, no race conditions, no collisions between parallel jobs. Pair it with a trap to clean up reliably.

What it does

mktemp atomically creates a temporary file (or directory with -d) with a unique name and prints its path. This avoids the security and collision problems of hardcoded /tmp/myfile names, especially with concurrent jobs.

Common usage

Terminal
tmp=$(mktemp)                   # unique temp file
dir=$(mktemp -d)                # unique temp directory
trap 'rm -rf "$tmp" "$dir"' EXIT   # always clean up
tmp=$(mktemp -t prefix.XXXXXX)  # with a name prefix
mktemp -d -p /var/tmp

Options

FlagWhat it does
-d / --directoryCreate a directory instead of a file
-tUse TMPDIR with a template (portable-ish)
-p <dir> / --tmpdirPlace it under a specific directory (GNU)
-u / --dry-runPrint a name without creating it (unsafe)
TEMPLATE.XXXXXXTrailing X's become random chars

Common errors in CI

"mktemp: too few X's in template" - the template needs at least 6 trailing X characters. GNU and BSD/macOS differ: macOS mktemp requires a template or -t prefix and treats -p/-t differently, so scripts that work on Linux can fail on Mac runners. Always quote "$tmp" (paths can contain spaces) and set a trap to rm -rf it on EXIT, or temp dirs accumulate and fill the disk across runs.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →