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
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/tmpOptions
| Flag | What it does |
|---|---|
| -d / --directory | Create a directory instead of a file |
| -t | Use TMPDIR with a template (portable-ish) |
| -p <dir> / --tmpdir | Place it under a specific directory (GNU) |
| -u / --dry-run | Print a name without creating it (unsafe) |
| TEMPLATE.XXXXXX | Trailing 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.