Skip to content
Latchkey

mktemp Command Reference for CI Scripts

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

mktemp gives a collision-free, race-free temp path, which matters on shared self-hosted runners where two jobs may run side by side. Pair it with a trap for cleanup.

Common flags/usage

  • mktemp: create a temp file, print its path
  • -d: create a temp directory instead
  • TEMPLATE with trailing XXXXXX: control the name pattern
  • -t: place it under the system temp dir (TMPDIR)
  • -p DIR: create it under a specific directory

Example

shell
set -euo pipefail
WORKDIR=$(mktemp -d)
trap 'rm -rf "${WORKDIR}"' EXIT
curl -fsSL "${ARTIFACT_URL}" | tar -xz -C "${WORKDIR}"

In CI

Hardcoded paths like /tmp/build collide when two jobs share a self-hosted runner; mktemp -d gives each run its own directory. Always register a trap 'rm -rf "$WORKDIR"' EXIT immediately after creating it so a failed step still cleans up. Capture the path in a variable, since mktemp only prints it once.

Key takeaways

  • mktemp -d gives a collision-free temp dir, vital on shared runners.
  • Register a trap to rm -rf it on EXIT right after creating it.
  • Capture the printed path in a variable; mktemp emits it only once.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →