Sunday, May 15, 2011

Shell: Reading directory with spaces in filename

My friend asked me how do you read a directory which has spaces in file names and assign them to a variable.

For example if my directory test has a file `foo bar.txt'

for file in `ls`; do
    echo "$file"
done


does not work, the variable file is assigned `foo' and `bar.txt'.


There is more than one way to solve this problem.


1. This works on most of the systems.


for file in *; do
    echo "$file"
done


2. Will definitely work.


IFS='
'
for file in `ls`; do
    echo "$file"
done


or


IFS=`echo -en "\n\b"`
for file in `ls`; do
    echo "$file"
done


3. One of my favorites and most efficient.


find . -type f -print0 | while read -d $'\0' file; do
     echo "$file"
done