0

I wrote this code to make an Array containing my images:

listOfImages=(`find . -iname "*.png" 2>/dev/null`)

But the path could have spaces in it so I have to enclose every element in double quotes:

listOfImages=(`find . -iname "*.png" 2>/dev/null | sed -E -e 's/(.*)/"\1"/'`)

Normally when we print an Array's elements, it should not print the double quotes, example:

x=("a" "b")
for i in ${x[@]}
do
echo "$i"
done

And it prints:

a
b

But on my images Array, it prints with the double quotes which causes problems on the following codes on my script.

Demonstration:

for i in ${listOfImages[@]}
do
echo $i
done

And it prints:

"blocks/glass.png"
"blocks/glass_black.png"
Shayan
  • 734
  • 1
  • 13
  • 26

1 Answers1

1

The double quotes in the output of your sed command have no syntactical meaning, i.e. they don't delimit the start and end of filenames. They're just literal quotes in the strings that go into your array. They don't protect you in any way from a filename like my image.png becoming two elements in your array.

Before making things more complicated, I'm wondering if you can use globstar to do a recursive expansion and get all your files ending with .png:

shopt -s globstar # enable recursive expansion of **
listOfImages=( **/*.png )

You almost always should loop through an array like:

for img in "${listOfImages[@]}" # quotes around the expansion

These quotes have syntactic meaning and prevent word-splitting from happening to the elements in your array, so my image.png is treated as a single element in the list.

Tom Fenech
  • 69,051
  • 12
  • 96
  • 131