[Linux] Create Secure Temporary Files and Directories with the mktemp Command

目次

Overview

The mktemp command is used to create unique temporary files or directories in shell scripts and other processes to avoid naming conflicts. It automatically generates filenames containing random characters, which helps avoid security risks like symbolic link attacks that can occur with predictable filenames.

Specifications (Arguments and Options)

Syntax

mktemp [options] [template]

Main Arguments and Options

OptionDescription
-d / –directoryCreates a temporary directory instead of a file.
-u / –dry-runGenerates and displays a name without actually creating the file (not recommended).
-q / –quietSuppresses error messages if file creation fails.
-p [DIR] / –tmpdir=[DIR]Creates the file within the specified directory (defaults to /tmp).
-tTreats the template as a suffix and creates the file in the temporary directory.
[template]Specifies a pattern for the filename. It must end with consecutive ‘X’s, which are replaced by random characters.

Basic Usage

When run without options, the command creates a file with a random name in the system’s default temporary area (usually /tmp) and displays its path.

# Create a secure temporary file
mktemp

Example Result:

/tmp/tmp.s83kL9zW2a

Note: An empty file is created immediately with 600 permissions (read/write only for the owner).

Practical Commands

Storing in a Variable for Use in Scripts

In shell scripts, it is standard to store the resulting path in a variable for later use.

#!/bin/bash

# Create a temporary file and store the path in TMP_FILE
TMP_FILE=$(mktemp)

# Display the created file path
echo "Temporary file created at: $TMP_FILE"

# Write to the temporary file
echo "Processing data..." > "$TMP_FILE"

# Delete the file after processing (essential)
rm "$TMP_FILE"

Creating with a Specific Name and Extension (Using Templates)

If you need to keep a specific prefix or extension, use a template with ‘X’s. You should use at least six ‘X’ characters.

# Create "app_log.random.txt" in the current directory
mktemp app_log.XXXXXX.txt

Example Result:

app_log.uH7b2s.txt

Automating Deletion (Using the trap Command)

To prevent temporary files from remaining if a script is interrupted or crashes, use the trap command to ensure deletion.

#!/bin/bash
# Create a temporary file
TMP_FILE=$(mktemp)

# Schedule the file for deletion on script exit (EXIT) or interruption (SIGINT)
trap 'rm -f "$TMP_FILE"' EXIT

# Main process
echo "Start processing..."
# The file will be deleted even if an error occurs here

Customization Tips

  • Specifying a Directory (-p): Use this to create files in a specific working directory instead of /tmp.Bashmktemp -p /var/www/html/uploads upload_check.XXXXXX
  • Dry Run (-u): This generates a name without creating the file. This is not recommended for secure scripts because another process could create a file with that same name before you do (a Race Condition).

Important Notes

  • Manual Deletion Required: mktemp does not automatically delete files. You must use rm in your script or use the trap command.
  • Number of X’s: If you provide too few ‘X’s, the command may fail to generate a unique name. Using XXXXXX (six) or more is recommended.
  • Permissions: By default, files are created with 600 permissions. If other users need to read the file, you must use chmod after creation.

Advanced Usage

Creating a Temporary Working Directory (-d)

Use the -d option if you need a temporary folder to hold multiple files.

# Create a temporary directory and store the path in a variable
WORK_DIR=$(mktemp -d)

echo "Work dir: $WORK_DIR"

# Perform file operations inside the directory
touch "${WORK_DIR}/data1.txt"
touch "${WORK_DIR}/data2.txt"

# Delete the entire directory and its contents at the end
rm -rf "$WORK_DIR"

Summary

The mktemp command is essential for creating unpredictable filenames, which makes your scripts more secure and robust. Always follow the pattern of creating a file with mktemp, storing it in a variable, and ensuring its deletion with trap.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次