Skip to content

Instantly share code, notes, and snippets.

@elfeffe
Forked from colinmollenhour/optimize_media.sh
Created October 18, 2016 09:10
Show Gist options
  • Save elfeffe/0babdf8669283ffb773c6cedf285ca1e to your computer and use it in GitHub Desktop.
Save elfeffe/0babdf8669283ffb773c6cedf285ca1e to your computer and use it in GitHub Desktop.
Optimize PNG and JPEG images - incrementally
#!/bin/bash
#
# Optimize all jpg and png files in the cwd
# Run it again to optimize new files since the last run
#
# Example:
# echo "optimize_media.sh > /tmp/optimize.log" | sudo -u www-data bash -s
#
# Colin Mollenhour 2016
user=www-data
dir=$PWD
flag=$dir/.last-optimized
[ $(whoami) = "$user" ] || { echo "Use 'sudo -u $user' to run this script." >&2; exit 1; }
type optipng 2>&1 > /dev/null || { echo "optipng is not installed." >&2; exit 1; }
type jpegoptim 2>&1 > /dev/null || { echo "jpegoptim is not installed." >&2; exit 1; }
touch ${flag}-new || { echo "Cound not touch new flag file." >&2; exit 1; }
date; du -sh $dir
opts="-type f"
if [ -f "$flag" ]; then
opts="$opts -newer $flag"
fi
find $dir $opts -iname '*.png' -not -path "*/watermark/*" \
-exec optipng -o7 -preserve {} \;
find $dir $opts \( -iname '*\.jpg' -or -iname '*\.jpeg' \) \
-exec jpegoptim --strip-all -p {} \; \
-exec chmod 660 {} \;
date; du -sh $dir
mv ${flag}-new $flag
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment