mktemp — Create safe temporary files and directories
Linux / File and disk management / mktemp.html
Creates temporary files or directories with random names to avoid collisions and predictable-name attacks.
Basic Information
| Command Name | mktemp |
|---|---|
| One-line Introduction | Creates temporary files or directories with random names to avoid collisions and predictable-name attacks. |
| Provided by | GNU coreutils (installed by default on all Linux distributions) |
| Official Documentation | https://man7.org/linux/man-pages/man1/mktemp.1.html |
| Supported Operating Systems | Linux, macOS, BSD, WSL |
| Installation Status | Installed by default (no separate installation needed) |
| Category | Linux 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"