Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to find certain files on my external disc and delete those. I created following script (to test I only use ls $i to check the output)

for i in `find /media/My\ Book/ -name "OP_CACHE.IDX" -print`; 
  do ls $i; 

The problem is, that the find-command returns just strings where the whitespaces (e.g. "My Book") are not encoded (like i do in /media/My\ Book) and hence I get errors that the folders cannot be found.

How can I solve this problem with the whitespaces? Is there a flag for find, or something?

regards Marc

share|improve this question
for i in something is a known bash pitfall. – Anonymous Jan 13 '10 at 16:19
up vote 5 down vote accepted

There is a flag for find, and it's used like this:

find "/media/My Book" -name "OP_CACHE.IDX" -exec ls {} \;

This can be used too:

find "/media/My Book" -name "OP_CACHE.IDX" -print0 | xargs -0 ls

(The -print0 argument tells find to separate filenames by null bytes, not by newlines. In most modern filesystems (ext3 and NTFS for example), filenames can contain not just spaces but also newlines, tabs, everything except a null byte. While it is very unlikely for your own disk to have such filenames, I tend to be careful about that.)

If you are going to just delete the files later, find can do that too:

find "/media/My Book" -name "OP_CACHE.IDX" -delete

(You can even use -print -delete to see each file as it's being removed.)

If you absolutely must use a bash loop, this will work most of the time:

find "/media/My Book" -name "OP_CACHE.IDX" | while read file; do
  ls "$file"

But see the comment about -print0 above.

share|improve this answer
Thanks for the detailed help. – lostiniceland Jan 13 '10 at 18:13

You should pipe your find into while read:

find ... | while read i
share|improve this answer

Instead of using for ..., use while read, like so:

find .... | while read LINE ; do
  ls "$LINE"

It will read one line at a time and put it in the LINE variable. Thus it doesn't matter if find doesn't escape the spaces. I have also wrapped the ls in "'s, which prevent a space there from messing it up

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.