0PricingLogin
Linux Command Line & Bash Scripting Mastery · Lesson

Safe Temporary Files and Lock Directories

Use mktemp and flock to create race-free temp resources and prevent concurrent script runs.

Why Temporary Files Are a Security Risk

Bash scripts frequently need temporary storage — intermediate results, lock markers, staging areas. But creating temp files carelessly opens serious vulnerabilities.

  • Race conditions: Another process can predict your filename and create the file first, redirecting your writes.
  • Symlink attacks: An attacker creates a symlink at your expected path pointing to a sensitive file like /etc/passwd.
  • Leftover files: If a script crashes, temp files pile up and may expose sensitive data.

The two core tools that eliminate these problems are mktemp and flock. This lesson shows you how to use both safely and defensively.

Creating Safe Temp Files with mktemp

mktemp creates a temporary file with a random, unpredictable name and returns its path. It atomically creates the file, so no other process can grab the name first.

  • Syntax: mktemp [TEMPLATE] — the template must end in at least three X characters.
  • Each X is replaced by a random character, producing a unique name like /tmp/script.aB3kQz.
  • The file is created with permissions 0600 (readable only by the owner) automatically.

Always capture the returned path into a variable immediately so you can reference and clean it up later.

#!/usr/bin/env bash
set -euo pipefail

# Create a secure temp file
TMPFILE=$(mktemp /tmp/myapp.XXXXXX)
echo "Temp file created at: $TMPFILE"

# Write data to it
echo "some intermediate result" > "$TMPFILE"

# Read it back
cat "$TMPFILE"

# Clean up
rm -f "$TMPFILE"

All lessons in this course

  1. Strict Mode with set -euo pipefail
  2. Trap Handlers for Cleanup and Signals
  3. Safe Temporary Files and Lock Directories
  4. Idempotent Scripts and Retry-with-Backoff Logic
← Back to Linux Command Line & Bash Scripting Mastery