Skip to content

Linux mktemp Guide

Mattscreative edited this page Dec 5, 2025 · 2 revisions

Linux mktemp Guide

Complete beginner-friendly guide to mktemp on Linux, covering Arch Linux, CachyOS, and other distributions including temporary file creation, secure temp files, and temporary directories.


Table of Contents

  1. mktemp Basics
  2. Temporary Files
  3. Temporary Directories
  4. Template Format
  5. Troubleshooting

mktemp Basics

Create Temp File

Basic usage:

# Create temporary file
mktemp

# Creates file in /tmp/
# Returns filename

Use in Script

Assign to variable:

# In script
TEMP_FILE=$(mktemp)
echo "Data" > "$TEMP_FILE"
# Use file
rm "$TEMP_FILE"

Temporary Files

Default Location

System temp:

# Creates in /tmp/
mktemp

# Output: /tmp/tmp.XXXXXX

Custom Location

Specify directory:

# Custom location
mktemp /tmp/myfile.XXXXXX

# Creates in specified location

Temporary Directories

Create Directory

Temp directory:

# Create directory
mktemp -d

# -d = directory (creates directory)

Use Directory

In script:

# Create temp directory
TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR"
# Use directory
cd -
rm -r "$TEMP_DIR"

Template Format

Template Pattern

Custom template:

# Template format
mktemp /tmp/myscript.XXXXXX

# X's replaced with random characters

Multiple X's

More randomness:

# More X's = more random
mktemp /tmp/file.XXXXXXXXXX

# More random characters

Troubleshooting

mktemp Not Found

Check installation:

# mktemp is part of coreutils
# Usually pre-installed

# Check mktemp
which mktemp

Summary

This guide covered mktemp usage, temporary file creation, and secure temp files for Arch Linux, CachyOS, and other distributions.


Next Steps


This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.

Clone this wiki locally