BASH

Create and Manage Temporary Files and Directories

Learn how to safely create unique temporary files and directories using `mktemp` in Bash scripts, ensuring isolation and preventing naming conflicts for transient data storage.

#!/bin/bash

# Ensure script exits if any command fails
set -e

echo "--- Creating Temporary Files and Directories ---"

# 1. Create a temporary file
# mktemp will create a unique file name and create the file
TEMP_FILE=$(mktemp /tmp/my-app.XXXXXX.tmp)
echo "Created temporary file: $TEMP_FILE"

# Write some data to the temporary file
echo "This is some temporary data." > "$TEMP_FILE"
echo "Current date: $(date)" >> "$TEMP_FILE"
echo "Content of $TEMP_FILE:"
cat "$TEMP_FILE"
echo ""

# 2. Create a temporary directory
# mktemp -d will create a unique directory name and create the directory
TEMP_DIR=$(mktemp -d /tmp/my-app-dir.XXXXXX)
echo "Created temporary directory: $TEMP_DIR"

# Create files inside the temporary directory
echo "File 1 content" > "$TEMP_DIR/data1.txt"
echo "File 2 content" > "$TEMP_DIR/data2.txt"
echo "Listing contents of $TEMP_DIR:"
ls -l "$TEMP_DIR"
echo ""

# 3. Use temporary files for intermediate processing
# Example: filter some data and store in a temp file
MESSAGE="Hello World
This is a test
Another line"
FILTERED_DATA_FILE=$(mktemp)
echo -e "$MESSAGE" | grep "test" > "$FILTERED_DATA_FILE"
echo "Filtered data stored in $FILTERED_DATA_FILE:"
cat "$FILTERED_DATA_FILE"
echo ""

# Important: Clean up temporary resources when done
echo "--- Cleaning up temporary resources ---"
if [ -f "$TEMP_FILE" ]; then
  rm "$TEMP_FILE"
  echo "Removed temporary file: $TEMP_FILE"
fi

if [ -d "$TEMP_DIR" ]; then
  rm -rf "$TEMP_DIR"
  echo "Removed temporary directory: $TEMP_DIR"
fi

if [ -f "$FILTERED_DATA_FILE" ]; then
  rm "$FILTERED_DATA_FILE"
  echo "Removed temporary file: $FILTERED_DATA_FILE"
fi

echo "Script finished."
How it works: This snippet demonstrates `mktemp` for creating unique temporary files and directories, preventing naming collisions. `mktemp /path/to/prefix.XXXXXX.tmp` creates a file, and `mktemp -d /path/to/prefix.XXXXXX` creates a directory. The `XXXXXX` part is replaced by a random string to ensure uniqueness. The example shows how to write to these temporary resources and then importantly, how to clean them up with `rm` and `rm -rf` once they are no longer needed, using conditional checks (`-f` for file, `-d` for directory) for robustness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs