Last Updated: February 25, 2016
· robinsmidsrod

Running any command on a directory tree containing files with spaces

Usually the common way to do an iteration of files and then perform some action on them is with the for loop in Bash.

for name in $(find . -type f | sort); do file "$name"; done

The problem is that it splits on whitespace, which isn't what we really want, we want it to split on newline only. By using a while loop + read you can avoid the problem all together and have a cleaner pipeline.

find . -type f | sort | while read name; do file "$name"; done

Originally mentioned at http://www.linuxjournal.com/content/bash-quoting#comment-345464

Say Thanks
Filed Under