BASH
Creating and Cleaning Up Temporary Directories
A robust bash script pattern for creating a temporary directory, performing operations within it, and ensuring its automatic cleanup on exit.
#!/bin/bash
# Create a temporary directory, perform operations, and ensure cleanup on exit.
# Create a unique temporary directory
TMP_DIR=$(mktemp -d -t myapp-XXXXXXXXXX)
# Check if temporary directory was created successfully
if [ ! -d "$TMP_DIR" ]; then
echo "Error: Could not create temporary directory." >&2
exit 1
fi
echo "Created temporary directory: $TMP_DIR"
# Ensure the temporary directory is removed when the script exits (normally or abnormally)
cleanup() {
echo "Cleaning up temporary directory: $TMP_DIR"
rm -rf "$TMP_DIR"
}
trap cleanup EXIT # Register cleanup function to run on script exit
# --- Your script's operations within the temporary directory ---
echo "Performing operations in $TMP_DIR..."
# Example: Create a file in the temporary directory
echo "This is a temporary file content." > "$TMP_DIR/temp_file.txt"
ls -l "$TMP_DIR"
# Example: Copy some files into the temp directory
# cp /path/to/some/file "$TMP_DIR/"
# Simulate some work
sleep 2
echo "Operations completed."
# --- End of operations ---
exit 0 # Explicitly exit, trap will still run
How it works: This script demonstrates a best practice for managing temporary files and directories in bash. It uses `mktemp -d` to create a unique temporary directory, then sets up a `trap cleanup EXIT` to ensure that this directory and its contents are automatically removed when the script finishes, whether it exits normally or due to an error. This prevents clutter and potential security risks from leftover temporary data.