Skip to content

Instantly share code, notes, and snippets.

@joeke
Created August 10, 2022 12:13
Show Gist options
  • Save joeke/f71c33e8b0c90fbc0504863d36633c17 to your computer and use it in GitHub Desktop.
Save joeke/f71c33e8b0c90fbc0504863d36633c17 to your computer and use it in GitHub Desktop.
webp-convert
#!/bin/bash
# Example run: ./webp-convert.sh /var/www/vhost/domain.nl/webroot
# cleanup, remove webp if jpg/png version does not exist or jpg/png is newer then webp version
echo -e "\033[0;34mCleaning up WEBP images\033[0m"
find $1 -type f -and -iname "*.webp" | while read webpFile; do
echo "Processing file '$webpFile'"
basename="${webpFile%.*}"
# Check if original file still exists.
[[ ! -z `find $basename{.png,.jpg,.jpeg} 2>/dev/null` ]] && remove=false || remove=true
# If original file still exists, check if the mtime of the webp version is newer then the original file mtime
if [ $remove == 'false' ]; then
echo 'Check if webp is older then original';
# Retrieve the path of the png/jpg/jpeg file.
originalFile=`find $basename{.png,.jpg,.jpeg} 2>/dev/null`
# Check if mtime of webp is newer then png/jpg/jpeg version of the file.
if [[ $originalFile -nt $webpFile ]]; then
remove=true
fi
fi
if [ $remove == 'true' ]; then
echo -e "\033[0;33mREMOVING: $webpFile, no original image found or original is newer then WEBP version. \033[0m"
rm $webpFile
fi
done
# converting JPEG images
echo -e "\033[0;34mConverting JPEG images\033[0m"
find $1 -type f -and \( -iname "*.jpg" -o -iname "*.jpeg" \) \
-exec bash -c '
webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$0");
if [ ! -f "$webp_path" ]; then
cwebp -quiet -q 90 "$0" -o "$webp_path";
fi;' {} \;
# converting PNG images
echo -e "\033[0;34mConverting PNG images\033[0m"
find $1 -type f -and -iname "*.png" \
-exec bash -c '
webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$0");
if [ ! -f "$webp_path" ]; then
cwebp -quiet -lossless "$0" -o "$webp_path";
fi;' {} \;
echo -e "\033[0;34mFinished cleaning up WEBP images\033[0m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment