Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File names with spaces in BASH

Tags:

linux

bash

I'm trying to write script that'll crop and resize large photos into HD Wallpapers.

#! /bin/bash


for i in `ls *.jpg`
do
    width=`identify -format '%w' $i`
    height=`identify -format '%h' $i`

    if [ `echo "$width/$height > 16/9" | bc -l` ]
    then
        exec `convert $i -resize 1920 -gravity Center -crop '1920x1080+0+0' +repage temp`
    else
        exec `convert $i -resize x1080 -gravity Center -crop 1920x1080+0+0 +repage temp`
    fi

    rm $i
    mv temp $i
done

But it seems that the script has problems with file names having spaces (like Tumble Weed.jpg). How can I fix this?

like image 499
finemann Avatar asked Oct 19 '10 11:10

finemann


2 Answers

First, you don't need ls. By using ls in backtics, you implicitly make bash parse a string into a list, which splits by whitespaces. Instead, make bash generate the list and separate it without such quirks:

Also, you need to enclose all $i usages into quotes, to make bash substitute it as a whole, not as a string split to separate words.

Here's the script that demonstrates both ideas:

for i in *.jpg ; do 
  echo "$i";
done
like image 109
P Shved Avatar answered Oct 20 '22 12:10

P Shved


Use read to circumvent the problem with spaces. It looks a bit unnatural to write the loop like this but it works better:

find . -type f -iname "*.jpg" | while read i
do
    # your original code inside the loop using "$i" instead of $i
done

with -iname you also get the jpg files that might have an extension with different casing like .JPG. "i" in "iname" means ignore casing.

like image 24
jdehaan Avatar answered Oct 20 '22 10:10

jdehaan