Shell – How to write a script to automatically optimize all the PNGs in the MediaWiki images directory

debianoptimizationpngshell-script

I have MediaWiki 1.25.2 installed on my 64-bit Debian 8.1 VirtualBox machine and I'd like to be able to upload the images/ directory from this installation to my DropBox. Being a cheapskate I'm trying to minimize the size of this images directory by optimizing the PNGs found therein with optipng, so that I don't end up with a DropBox that's so full that I need to pay for more storage. My Wiki has at the moment 182 PNGs that I have uploaded to it (along with well over a hundred others that are thumbnails of these original PNGs and of the SVGs I have on my Wiki), so running optipng -o7 <filename> on each of these files manually will be very tedious.

Hence I am here asking, how I might write a bash script that will automatically do this for me. Now I know some pieces of the puzzle of how to do this, like I know that the find program can generate lists of files with a specified file extension in a specified location (e.g., running sudo find . -type f -name "*.png" from the images/ directory which for me is at /var/lib/mediawiki/images will list all the PNGs therein), but I don't know how to use this program to create a text file containing all the file names relative to this directory (e.g., f/f1/Frugalware_Linux_screenshot.png). I also don't know how to get optipng to optimize PNGs listed in a text file.

Best Answer

Try:

for i in `find . -type f -name "*.png"`
do
  optipng -o7 "$i"
done

Did not test it but it should work like that. If you need to test it then you might change the line optipng -o7 $i with echo $i to see if you get the correct file.

Related Question