Escape variables with filenames that have spaces

199 Views Asked by At

I'm using this line to batch my pngcrush, yet my files contain spaces, which get's placed literally into $line, making them get skipped as they aren't valid paths:

ls *.png | while read line; do pngcrush -brute $line compressed/$line; done

How can I make $line become escape like this filename Button - Users.png would be replaced with Button\ -\ Users.png?

2

There are 2 best solutions below

0
On BEST ANSWER

Don't parse the output of ls. Use a for loop here instead.

for f in *.png; do
    pngcrush -brute "$line" compressed/"$line"
done
0
On

Simply enclose variables in double-quotes. It's a good practice ever:

ls *.png | while read line; do pngcrush -brute "$line" "compressed/$line"; done