24 July 2008

for, find, and whitespace

I recently wrote a short bash script to create thumbnails of all of my images and place them into a single directory. Basically I needed a bunch of images that I could do some testing with. It seemed like a simple enough task, but then I ran into the dreaded bash whitespace problem. This seems to be an issue for a lot of people but it still took a long time to find a solution that would work in my case.

Here is an illustration of the problem I had.
for FILE in `find`
do
  echo $FILE
done
In this example if a file or directory has the name "My File", the for loop will iterate once for the word "My" and once for the word "File". By default bash parses the string and splits it on tabs, spaces, and newlines. You can fix this a few different ways. The best way I determined was to change what bash considers to be whitespace. You do that by changing the value of IFS.
export IFS=$'\n'
for FILE in `find`
do
  echo $FILE
done
After figuring that out the rest of the script was pretty easy. The complete script is below for anyone who might like to do the same thing. This was a quick hack to work for my situation and you will certainly need to adjust things for what you need.
export IFS=$'\n'
for PATH in `find /Users/username/Pictures/ -type f -name '*.jpg' \
        -o -name '*.gif' -o -name '*.jpeg' \
        -o -name '*.tif' -o -name '*.png'`
do
 FILE=${PATH##*/}
 /usr/local/bin/convert -size 180x180 $PATH -thumbnail 90x90 images/$FILE
done

No comments: