Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script for JPEG images optimization
#! /bin/sh
# Usage 1:
# optimize-images.sh /images/dir
#
# Usage 2:
# cd /images/dir
# optimize-images.sh
EXTENSIONS="jpe?g"
if [ -z "$1" ]; then
DIR="`pwd`"
else
DIR="$1"
fi
# Optimize JPEG images
find "$DIR" -regextype posix-egrep -regex ".*\.($EXTENSIONS)\$" -type f | xargs -I{} jpegtran -optimize -progressive -outfile "{}.optimized" "{}"
# Rename xxx.jpg.optimized -> xxx.jpg
find "$DIR" -name '*.optimized' -print0 | while read -d $'\0' file; do
chown $(stat -c "%U:%G" "${file%.optimized}") "$file"
chmod $(stat -c "%a" "${file%.optimized}") "$file"
mv -f "$file" "${file%.optimized}";
done
@swatinuna
Copy link

swatinuna commented Sep 10, 2015

Hello,

This script does not work when run inside directories with spaces and quotes in their name.

Please suggest for solve this.

@tazman
Copy link

tazman commented Nov 23, 2016

Hello. Thx for the script first of all
i have the error runnig your script
./optimize-images.sh: 22: read: Illegal option -d

@mordka
Copy link

mordka commented Jul 4, 2017

@tazman you may try changing #! /bin/sh to #!/bin/bash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment