Bash and Spaces

David Anselmi gave me some help with loops in bash--in particular with having spaces in filenames. Bash thinks spaces indicate separate tokens to iterate over. As you can read below, a solution using read works.

Re: [CLUE-Tech] bash and spaces
David Anselmi
Tue, 09 Nov 2004 12:34:15 -0700

Angelo Bertolli wrote:

Can someone explain why this has a problem with spaces in the filename?

for log in `locate WS_FTP.LOG`; do cat "$log" >> ~root/WS_FTP_ALL2.LOG; done

Ok, here you go:

locate WS_FTP.LOG | while read log ; do cat "$log" >> \
~root/WS_FTP_ALL2.LOG; done

You might also get the same result putting the >> after the done, in which case you could use > instead if truncation between invocations is what you really wanted.

The problem with for is that it iterates over each word after the in and words are separated by spaces.  So a space in a path means multiple words to for.

If you quote your command substitution the quotes prevent word splitting but then all your output from locate is one word.  The for loop runs once and the argument to cat is one word (with newlines in it) that doesn't match any file names.  With a command like echo it might not matter but with cat it does.

The only thing that seems to help is to remove spaces from $IFS but that seems clumsy to me and might cause other parts of your command to behave unexpectedly.

BTW, you can find all this on google and bash(1).