[CLUE-Tech] bash and spaces

David Anselmi anselmi at anselmi.us
Tue Nov 9 12:34:15 MST 2004


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).

HTH,
Dave




More information about the clue-tech mailing list