Skip to content

Instantly share code, notes, and snippets.

@swikars1
Created July 7, 2025 04:55
Show Gist options
  • Select an option

  • Save swikars1/305ac421a91e3655c8ea235f7ee433d3 to your computer and use it in GitHub Desktop.

Select an option

Save swikars1/305ac421a91e3655c8ea235f7ee433d3 to your computer and use it in GitHub Desktop.
Pre Commit for Cache Busting for js and css
#!/bin/bash
# Function to bump version number in a string (e.g., 2.3 → 2.4)
bump_version() {
local version=$1
local major=$(echo $version | cut -d. -f1)
local minor=$(echo $version | cut -d. -f2)
minor=$((minor + 1))
echo "$major.$minor"
}
# Get list of staged js and css files
changed_files=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|css)$')
if [ -z "$changed_files" ]; then
echo "No JS or CSS files changed. Skipping version bump."
exit 0
fi
# Files to search for references (adjust extensions as needed)
search_files=$(git ls-files | grep -E '\.(html|jsp|htm)$')
for changed_file in $changed_files; do
# Extract filename only
filename=$(basename "$changed_file")
# Escape slashes for grep using alternate delimiter for sed
escaped_filename=$(echo "$filename" | sed 's|/|\\/|g')
# For each search file, check if it contains reference to changed file with version param
for file in $search_files; do
if grep -q "$escaped_filename?v=" "$file"; then
# Extract current version using grep -E and sed instead of grep -P
current_version=$(grep -Eo "$escaped_filename\?v=[0-9]+\.[0-9]+" "$file" | head -1 | sed -E "s/.*\?v=([0-9]+\.[0-9]+)/\1/")
if [ -n "$current_version" ]; then
new_version=$(bump_version "$current_version")
# Replace old version with new version using sed with backup suffix for macOS
sed -i.bak "s/$escaped_filename?v=$current_version/$escaped_filename?v=$new_version/g" "$file"
rm -f "$file.bak"
echo "Bumped version of $filename in $file from $current_version to $new_version"
# Stage the modified file
git add "$file"
fi
fi
done
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment