Skip to content

Instantly share code, notes, and snippets.

@joeke
Created August 10, 2022 12:23
Show Gist options
  • Save joeke/561124c32c50d783d700e73648946f01 to your computer and use it in GitHub Desktop.
Save joeke/561124c32c50d783d700e73648946f01 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Example run: ./optimize-images.sh -path /var/www/vhost/domain.nl -mtime 2
# Example run with exclude: ./optimize-images.sh -path /var/www/vhost/domain.nl -mtime 2 -exclude "*/exclude_dir/*"
mtime='2'
path=''
exclude=''
find_path="$(which find)"
optipng_path="$(which optipng)"
jpegoptim_path="$(which jpegoptim)"
usage() {
cat << EOF >&2
Usage: optimize-images [-mtime <mtime>] [-path <path>]
-mtime <mtime>: Only optimize files which have been modified within X amount of days.
-path <path>: Path where the images will be optimized. For example: /var/www/vhost
EOF
exit 1
}
[ -z $1 ] && { usage; }
parse_args() {
case "$1" in
-mtime)
mtime="$2"
;;
-path)
path="$2"
;;
-exclude)
exclude="-not -path $2"
;;
*)
echo "Unknown or badly placed parameter '$1'." 1>&2
exit 1
;;
esac
}
while [[ "$#" -ge 2 ]]; do
parse_args "$1" "$2" "$3"
shift; shift
done
echo "Only optimize files which have been modified within:" $mtime "days."
echo "Use" $path "as folder where the images will be optimized."
echo "------------------------------------"
echo "Start optimizing PNG images:" `date`
echo "------------------------------------"
$find_path $path -mtime -$mtime -iname "*.png" $exclude -exec $optipng_path -o2 -strip all -preserve '{}' \;
echo "------------------------------------"
echo "Finished optimizing PNG images: " `date`
echo "------------------------------------"
echo "------------------------------------"
echo "Start optimizing JPEG images:" `date`
echo "------------------------------------"
$find_path $path -mtime -$mtime -iname "*.jpeg" $exclude -exec $jpegoptim_path --max=80 --strip-all --preserve --totals '{}' \;
$find_path $path -mtime -$mtime -iname "*.jpg" $exclude -exec $jpegoptim_path --max=80 --strip-all --preserve --totals '{}' \;
echo "------------------------------------"
echo "Finished optimizing JPEG images: " `date`
echo "------------------------------------"
# Optional GIF compression (Uses gifsicle & giflossy for lossy compression)
# gifsicle_path="$(which gifsicle)"
# echo "------------------------------------"
# echo "Start optimizing GIF images:" `date`
# echo "------------------------------------"
# $find_path $path -mtime -$mtime -iname "*.gif" -exec $gifsicle_path --batch -O3 --lossy=80 -O '{}' \;
# echo "------------------------------------"
# echo "Finished optimizing GIF images: " `date`
# echo "------------------------------------"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment