Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read the contents of a directory using shell script

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.

like image 657
jrharshath Avatar asked Mar 12 '10 19:03

jrharshath


2 Answers

for entry in *
do
  echo "$entry"
done
like image 80
Ignacio Vazquez-Abrams Avatar answered Oct 19 '22 23:10

Ignacio Vazquez-Abrams


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
like image 28
ghostdog74 Avatar answered Oct 20 '22 01:10

ghostdog74