linuxbashshell

Iterate over a list of files with spaces


I want to iterate over a list of files. This list is the result of a find command, so I came up with:

getlist() {
  for f in $(find . -iname "foo*")
  do
    echo "File found: $f"
    # do something useful
  done
}

It's fine except if a file has spaces in its name:

$ ls
foo_bar_baz.txt
foo bar baz.txt

$ getlist
File found: foo_bar_baz.txt
File found: foo
File found: bar
File found: baz.txt

What can I do to avoid the split on spaces?


Solution

  • You could replace the word-based iteration with a line-based one:

    find . -iname "foo*" | while read f
    do
        # ... loop body
    done