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
trap Command Reference for CI Scriptstrap runs cleanup handlers on signals and exit in CI scripts. Reference for EXIT, ERR, and signal traps so te…
rm -rf Command Reference for CI Scriptsrm -rf removes files and directories in CI cleanup. Reference for -r, -f, and safe-deletion habits, plus the…
mkdir -p Command Reference for CI Scriptsmkdir -p creates directory trees idempotently in CI. Reference for -p, -m, and parent creation, plus why -p n…
mv Command Reference for CI Scriptsmv moves or renames files in CI for atomic artifact swaps. Reference for -f, -n, -t, and cross-filesystem beh…