Sunday, February 04, 2007

Shell Script to Parse Command Line Arguments

Problem: I needed a script that took just file names and translated large JPEG's into smaller or thumbnail images. The problem was the convert command, part of ImageMagick, needs the specific output file name.

Solution: The following script.
#!/bin/bash

if [ ! -d Thumbs ] ; then
mkdir Thumbs;
fi

while [ $# -ge 1 ]; do
TARGET=`echo -n "$1" | sed "s/.jpg/t.png/" | sed "s/.JPG/T.PNG/" | sed "s/.jpeg/t.png/" | sed "s/.JPEG/T.PNG/"`;
if [ -e $TARGET ] ; then
echo "Refusing to overwrite $TARGET. ";
else
echo -n "Converting $1 to Thumbs/$TARGET: ";
convert $1 -resize 128x128 Thumbs/$TARGET;

if [ $? -eq 0 ]
then
echo "OK."
else
echo "ERROR: $?"
fi

fi

shift

done
exit 0