Skip to content

Instantly share code, notes, and snippets.

@gazmull
Last active March 27, 2023 05:41
Show Gist options
  • Save gazmull/255364faf90e1156748eb7c363f9aeb1 to your computer and use it in GitHub Desktop.
Save gazmull/255364faf90e1156748eb7c363f9aeb1 to your computer and use it in GitHub Desktop.
[bash - cwebp] Converts all PNG/JPG/JPEG files in a directory (recursive) to WebP. Optional Forced flag to re-convert existing WebP files.
#!/bin/bash
# Tested at Debian 10 (Buster)
# Usage: ./cwebp.sh [-f] <directory>
forced=n
# If first arg contains forced flag (-f), remove first arg. Directory becomes first arg.
[ "$1" = "-f" ] && forced=y && shift && echo "Forced Mode Detected"
# List all regular files (JPG/JPEG/PNG) in the directory
# @ -exec:
# $0 = forced variable ($forced)
# $1 = File found by find command ({})
# ----------
# cwebp flags should be modified according to your preferences. It's configured to be the 3rd to the best compression.
# [!] Conversion errors are sent to void
# - cwebp Documentation: https://developers.google.com/speed/webp/docs/cwebp
find $1 -type f -and \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) \
-exec bash -c '
if [[ "$0" = "y" || ! -f "$1.webp" ]]; then
echo "Converting $1" && cwebp -short -lossless -z 7 "$1" -o "$1.webp" 2>/dev/null;
fi
' $forced {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment