Add hashes to CSS and JS file names and update their references in HTML documents.
Place the shell script into the same directory as htmldir
and cssjsdir
folders;
adjust the variables to whatever actual names are in use. Currently it only supports
relative paths to these two folders with respect to the script file.
However, it uses absolute paths in each HTML file with respect to htmldir
, so
that on the server itself each reference begins with /
(i.e. server root).
Because of this, the directory tree of cssjsdir
must match that of htmldir
.
Basic overview of how it works:
#!/bin/sh
- setup shell
export cssjsdir="css-js"
- set relative path of the folder containing CSS and JS subfolders with source files in them
export htmldir="html"
- set relative path of the folder containing HTML files
export shorthash=0
- if true, file names will only include the first eight characters of the
find "./""$cssjsdir" -type f \( -name '*.js' -o -name '*.css' \) -exec sh -c '
for file do
- find all files in
cssjsdir
folder and subfolders that are CSS or JS and exec below contents on the output
- find all files in
fdir=$(dirname "$file" | cut -c 3-65535 | sed s,"$cssjsdir""/",,g)
fname=$(basename "$file" | cut -d "." -f 1)
fext=$(basename "$file" | cut -d "." -f 2)
- respectively gets the path (relative), name, and extension of current file
fhashfull=$(sha256sum "$file" | cut -d " " -f 1)
- generate SHA2 of current file
if [ "$shorthash" -eq 1 ]; then
fhash=$(echo "$fhashfull" | cut -c 1-8)
else
fhash="$fhashfull"
fi
- optionally trim the hash length
fpathfull="/""$fdir""/""$fname"-"$fhash"."$fext"
echo "$fpathfull"
- form path and name for the new file
mkdir -p "$htmldir"/"$fdir"
rm "$htmldir"/"$fdir"/"$fname"*"$fext"
cat "$file" > "$htmldir"/"$fdir"/"$fname"-"$fhash"."$fext"
- remove the existing file from
htmldir
and replace it with the new one
- remove the existing file from
for html in $(find ./"$htmldir" -type f \( -name "*.html" \)); do
- find all HTML files in
htmldir
- find all HTML files in
sed -i s,"/""$fdir""/""$fname".*"$fext","$fpathfull",g "$html"
- replace every reference to the current file with the new file
done
done
- end the for loops
' exec-sh {} +
- end of exec command
- (
\n
)- newline at EOF because git yells at me otherwise