read the contents of a directory using shell script
Asked Answered
H

2

8

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.

Hodgkin answered 12/3, 2010 at 19:47 Comment(1)
very related question: stackoverflow.com/questions/2437452Hodgkin
R
13
for entry in *
do
  echo "$entry"
done
Ringster answered 12/3, 2010 at 19:48 Comment(5)
Maybe you should use 'for entry in * .*'?Cryptography
@Jonathan: If you need to match files starting with a . then you're better off twiddling the dotglob option.Ringster
what is the dotglob option?Hodgkin
When dotglob is set (via shopt -s dotglob) * will match files that start with a ..Ringster
You've already accepted an answer for this question. Create a new one.Ringster
U
3

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
Undergraduate answered 13/3, 2010 at 0:42 Comment(1)
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 loopUndergraduate

© 2022 - 2024 — McMap. All rights reserved.