Using a loop such as
for i in `find . -name \*.txt`
will break if some filenames have spaces in them.
What technique can I use to avoid this problem?
Ideally you don't do it that way at all, because parsing filenames properly in a shell script is always difficult (fix it for spaces, you'll still have problems with other embedded characters, in particular newline). This is even listed as the first entry in the BashPitfalls page.
That said, there is a way to almost do what you want:
Remember to also quote
This does have one other caveat attached: what happens inside the
At some point the correct fix for all of this becomes doing it in a language such as Perl or Python instead of shell.
I disagree with the
Note that in most/many situations you do not need to set and reset IFS; just use IFS locally as shown in the examples below. All three handle whitespace fine. Also you do not need a "standard" loop structure, because find's
And, two more examples
Shell scripts aren't the best way to handle filenames with spaces in them: you can do it, but it gets clunky.
You can set the "internal field separator" (
Another method, depending on what you want to do with the output from