views:

301

answers:

2

Hi,

I'm trying to get the contents of a directory using shell script.

My script is:

for entry in `ls`; do
    echo $entry
done

However, my current directory contains many files with whitespaces in their names. In that case, this script fails.

What is the correct way to loop over the contents of a directory in shell scripting?

PS: I use bash.

+2  A: 
for entry in *
do
  echo "$entry"
done
Ignacio Vazquez-Abrams
+1 for being correct and faster than me! :-P
Buggabill
Maybe you should use 'for entry in * .*'?
Jonathan Leffler
@Jonathan: If you need to match files starting with a `.` then you're better off twiddling the `dotglob` option.
Ignacio Vazquez-Abrams
what is the `dotglob` option?
Here Be Wolves
When `dotglob` is set (via `shopt -s dotglob`) `*` will match files that start with a `.`.
Ignacio Vazquez-Abrams
okay.. thanks a lot :)
Here Be Wolves
Updated the question
Here Be Wolves
You've already accepted an answer for this question. Create a new one.
Ignacio Vazquez-Abrams
+1  A: 

don't parse directory contents using ls in a for loop. you will encounter white space problems. use shell expansion instead

   for file in *
    do
      if [ -f "$file" ];then
       echo "$file"
      fi
    done
ghostdog74
updated the question..
Here Be Wolves
that's bash syntax. try it and see. remember the double quotes around variables. This will preserve white spaces. Just don't use `ls` in the `for loop`
ghostdog74