BASH

Implement Simple Cache Busting for Static Assets

Prevent browser caching issues for updated static files by automatically appending a unique timestamp or hash to their filenames in your build process.

#!/bin/bash
# Usage: ./cache_bust.sh <source_directory> <target_directory> <file_extension>
# Example: ./cache_bust.sh ./dist/assets ./dist/assets css

SOURCE_DIR="$1"
TARGET_DIR="$2"
FILE_EXT="$3" # e.g., 'css', 'js', 'svg'

if [ -z "$SOURCE_DIR" ] || [ -z "$TARGET_DIR" ] || [ -z "$FILE_EXT" ]; then
    echo "Usage: $0 <source_directory> <target_directory> <file_extension>"
    echo "Example: $0 ./dist/assets ./dist/assets js"
    exit 1
fi

# Ensure target directory exists
mkdir -p "$TARGET_DIR"

# Generate a unique timestamp or hash for cache busting
CACHE_BUST_KEY=$(date +%s) # Using timestamp, or use `git rev-parse --short HEAD` for git hash

echo "Applying cache busting with key: $CACHE_BUST_KEY to files in '$SOURCE_DIR' (type: *.$FILE_EXT)"

find "$SOURCE_DIR" -type f -name "*.$FILE_EXT" | while read -r file; do
    FILENAME=$(basename "$file")
    BASENAME="${FILENAME%.*}"
    EXTENSION="${FILENAME##*.}"

    NEW_FILENAME="${BASENAME}.${CACHE_BUST_KEY}.${EXTENSION}"
    NEW_PATH="$TARGET_DIR/$NEW_FILENAME"

    # Copy and rename the file
    cp "$file" "$NEW_PATH"
    echo "Copied '$file' to '$NEW_PATH'"

    # Optional: If you want to delete original after successful copy (use with caution!)
    # rm "$file"

done

echo "Cache busting complete. Remember to update your HTML/CSS to reference the new filenames."
How it works: This script automates a simple cache busting strategy. It takes source and target directories, and a file extension. It generates a unique key (here, a timestamp, but could be a Git commit hash). It then iterates through all files of the specified extension in the source directory, renames them by inserting the `CACHE_BUST_KEY` before the extension (e.g., `style.1678881234.css`), and copies them to the target directory. This ensures that browsers request a new version of the asset whenever the key changes, bypassing stale caches.

Need help integrating this into your project?

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

Hire DigitalCodeLabs