Skip to main content

How to Create Temporary File

β€’ 2 min read
bash temporary files mktemp file handling cleanup security

Quick Answer: Create Temporary File in Bash

To create a temporary file safely, use mktemp: tmpfile=$(mktemp). This creates a unique file in /tmp with secure permissions. Always clean up with a trap: trap "rm -f $tmpfile" EXIT to ensure deletion even if script exits early.

Quick Comparison: Temporary File Methods

MethodSafetySecurityBest ForCleanup
mktempExcellentExcellentAll casesManual/trap
/tmp/file.$$GoodGoodSimpleManual
mktemp -dExcellentExcellentDirectoriesManual/trap

Bottom line: Always use mktemp for security; always set trap for cleanup.


Create and manage temporary files safely in Bash. Learn using mktemp, cleanup traps, and best practices.

The safest way to create temporary files:

# Create temporary file
tmpfile=$(mktemp)
echo "Temp file: $tmpfile"

# Create with specific prefix
tmpfile=$(mktemp /tmp/myapp.XXXXXX)

# Create temporary directory
tmpdir=$(mktemp -d)

Basic Example

#!/bin/bash

# Create temporary file
tmpfile=$(mktemp)

# Use it
echo "Processing data..." > "$tmpfile"
cat "$tmpfile"

# Clean up
rm "$tmpfile"

Auto-Cleanup with Trap

#!/bin/bash

# Create temp file
tmpfile=$(mktemp)

# Ensure cleanup on exit
trap "rm -f $tmpfile" EXIT

# Use temp file
echo "Data" > "$tmpfile"
# ... do work ...

# File automatically deleted when script exits

Named Temporary Files

# Create with specific name pattern
tmpfile=$(mktemp /tmp/backup.XXXXXX)

# X's are replaced with random characters
# Creates: /tmp/backup.a7k3Pq
echo "Backup data" > "$tmpfile"

# Remove explicitly
rm "$tmpfile"

Practical Example: Safe File Processing

#!/bin/bash

# File: process_file_safely.sh

input_file="$1"
output_file="$2"

if [ ! -f "$input_file" ]; then
  echo "ERROR: Input file not found"
  exit 1
fi

# Create temporary file
tmpfile=$(mktemp)

# Ensure cleanup
trap "rm -f $tmpfile" EXIT

# Process to temp file first
cat "$input_file" | \
  tr '[:lower:]' '[:upper:]' | \
  sort > "$tmpfile"

# If processing succeeded, move to output
if [ $? -eq 0 ]; then
  mv "$tmpfile" "$output_file"
  echo "βœ“ Processing complete: $output_file"
else
  echo "βœ— Processing failed"
  exit 1
fi

# Trap automatically cleans up on exit

Temporary Directory

#!/bin/bash

# Create temporary directory
tmpdir=$(mktemp -d)

# Cleanup on exit
trap "rm -rf $tmpdir" EXIT

# Use the directory
file1="$tmpdir/file1.txt"
file2="$tmpdir/file2.txt"

echo "Data 1" > "$file1"
echo "Data 2" > "$file2"

# ... do processing ...

# Directory and contents automatically deleted

Practical Example: Batch Processing

#!/bin/bash

# File: batch_process.sh

input_dir="$1"
output_dir="$2"

# Create temp work directory
workdir=$(mktemp -d)
trap "rm -rf $workdir" EXIT

echo "Processing files in: $input_dir"
echo "Temporary workspace: $workdir"
echo ""

for file in "$input_dir"/*; do
  if [ -f "$file" ]; then
    basename=$(basename "$file")
    tmpfile="$workdir/$basename"

    # Process to temporary file
    process_file "$file" > "$tmpfile"

    if [ $? -eq 0 ]; then
      # Move to output only if successful
      mv "$tmpfile" "$output_dir/$basename"
      echo "βœ“ Processed: $basename"
    else
      echo "βœ— Failed: $basename"
    fi
  fi
done

echo ""
echo "βœ“ All files processed"
# workdir automatically cleaned up

Temporary File with Content

#!/bin/bash

# Create temp file with initial content
tmpfile=$(mktemp)
trap "rm -f $tmpfile" EXIT

# Write initial content
cat > "$tmpfile" << 'EOF'
Line 1
Line 2
Line 3
EOF

# Use the file
sed 's/Line/Row/' "$tmpfile"

Multiple Temporary Files

#!/bin/bash

# Create multiple temp files
tmp1=$(mktemp)
tmp2=$(mktemp)
tmp3=$(mktemp)

# Cleanup all on exit
trap "rm -f $tmp1 $tmp2 $tmp3" EXIT

# Use them
echo "data1" > "$tmp1"
echo "data2" > "$tmp2"
echo "data3" > "$tmp3"

# Merge temporary files
cat "$tmp1" "$tmp2" "$tmp3" > result.txt

Temporary File in Specific Location

# Use different temp directory if needed
tmpdir="/scratch"

if [ ! -d "$tmpdir" ]; then
  tmpdir="/tmp"  # Fallback
fi

tmpfile=$(mktemp -p "$tmpdir")
trap "rm -f $tmpfile" EXIT

Check Temporary Availability

#!/bin/bash

# Check if mktemp works
if ! tmpfile=$(mktemp); then
  echo "ERROR: Cannot create temporary file"
  exit 1
fi

trap "rm -f $tmpfile" EXIT

# Use temporary file safely
echo "Processing..." > "$tmpfile"

Practical Example: Diff Two Commands

#!/bin/bash

# File: compare_commands.sh

cmd1="$1"
cmd2="$2"

# Create temp files for output
tmp1=$(mktemp)
tmp2=$(mktemp)

trap "rm -f $tmp1 $tmp2" EXIT

# Run commands and save output
eval "$cmd1" > "$tmp1"
eval "$cmd2" > "$tmp2"

# Compare outputs
if diff -q "$tmp1" "$tmp2" > /dev/null; then
  echo "Outputs are identical"
else
  echo "Outputs differ:"
  diff "$tmp1" "$tmp2"
fi

Usage:

$ ./compare_commands.sh "ls -la" "find . -maxdepth 1 -type f"

Safe Sort and Replace

#!/bin/bash

# Sort file in place safely

file="$1"
tmpfile=$(mktemp)

trap "rm -f $tmpfile" EXIT

# Sort to temp file
sort "$file" > "$tmpfile"

if [ $? -eq 0 ]; then
  # Only replace if sort succeeded
  mv "$tmpfile" "$file"
  echo "βœ“ File sorted"
else
  echo "βœ— Sort failed"
  exit 1
fi

Temporary Named Pipe

#!/bin/bash

# Create named pipe (FIFO)
tmpfifo=$(mktemp -u)
mkfifo "$tmpfifo"

trap "rm -f $tmpfifo" EXIT

# Write to pipe in background
(sleep 2; echo "delayed data") > "$tmpfifo" &

# Read from pipe
cat "$tmpfifo"

Error Handling

#!/bin/bash

# Proper error handling with temp files

create_temp_safely() {
  local tmpfile
  tmpfile=$(mktemp) || return 1

  trap "rm -f '$tmpfile'" EXIT

  if ! some_command > "$tmpfile" 2>&1; then
    echo "ERROR: Command failed"
    return 1
  fi

  cat "$tmpfile"
}

create_temp_safely || exit 1

Common Mistakes

  1. Not using mktemp - predictable filenames are a security risk
  2. Forgetting trap - temp files left behind on error
  3. Hardcoded /tmp paths - mktemp handles this
  4. Not quoting variables - β€œ$tmpfile” not $tmpfile
  5. Not handling mktemp failure - check exit code

Performance Tips

  • Use temp files only when necessary
  • Use pipes when possible instead of temp files
  • Clean up explicitly to avoid disk space issues
  • Monitor /tmp size for long-running processes

Key Points

  • Use mktemp for safe temporary file creation
  • Always set trap for cleanup
  • Quote variable names: "$tmpfile"
  • Use -d for temporary directories
  • Test mktemp success before using

Summary

Creating temporary files safely is crucial for bash scripts. Always use mktemp, set up cleanup traps, and quote variables properly. This prevents security issues and ensures proper cleanup on errors.