Korean

mktemp — Create safe temporary files and directories

Linux / File and disk management / mktemp.html

File and disk managementOriginalRegistered 2026-10-20T09:00:00+09:00

Creates temporary files or directories with random names to avoid collisions and predictable-name attacks.

Basic Information

Command Namemktemp
One-line IntroductionCreates temporary files or directories with random names to avoid collisions and predictable-name attacks.
Provided byGNU coreutils (installed by default on all Linux distributions)
Official Documentationhttps://man7.org/linux/man-pages/man1/mktemp.1.html
Supported Operating SystemsLinux, macOS, BSD, WSL
Installation StatusInstalled by default (no separate installation needed)
CategoryLinux file and disk management (tags: temporary file, security, script, coreutils)

What is this command?

mktemp creates a temporary file or directory with a unique name and prints its path. Hard-coded names in scripts can collide with other processes or enable symlink attacks.

The usual pattern is to store the printed path in a variable and clean it up with trap when the script exits.

What problems does it solve?

  • A script needs a safe temporary file
  • Parallel runs collide on the same file name
  • You need a temporary directory that is cleaned up
  • You want to avoid predictable-name security issues

Key features

Create a temp file

With a template it appends random characters to the pattern.

  • When to use: You need to store intermediate results
  • What you get: A safely created file and its path
  • Limitations: The default location is /tmp and may be cleared on reboot.

Create a temp directory

-d creates a directory instead of a file.

  • When to use: You want several temp files in one place
  • What you get: A randomly named directory
  • Limitations: You must clean up the contents yourself.

Create in a chosen location

-p sets the base directory.

  • When to use: You must use a volume other than /tmp
  • What you get: A temporary entry in that location
  • Limitations: Write permission on that directory is required.

Installation and usage

Check whether it is installed

mktemp --version

sudo apt install coreutils # Debian/Ubuntu sudo dnf install coreutils # Fedora

Real-world examples

Get a temp file path

Store the path in a variable for later commands.

tmp=$(mktemp)
echo "data" > "$tmp"
rm -f "$tmp"

Temp directory with cleanup

Use trap to remove it when the script exits.

workdir=$(mktemp -d)
trap 'rm -rf "$workdir"' EXIT
echo "$workdir"