How to get the list of files in a directory in a shell script?

Posted by jrharshath on Stack Overflow See other posts from Stack Overflow or by jrharshath
Published on 2010-03-13T06:03:45Z Indexed on 2010/03/13 6:05 UTC
Read the original article Hit count: 214

Hi,

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

My script is:

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

where $search_dir is a relative path. However, $search_dir contains many files with whitespaces in their names. In that case, this script does not run as expected.

I know I could use for entry in *, but that would only work for my current directory.

I know I can change to that directory, use for entry in * then change back, but my particular situation prevents me from doing that.

I have two relative paths $search_dir and $work_dir, and I have to work on both simultaneously, reading them creating/deleting files in them etc.

So what do I do now?

PS: I use bash.

© Stack Overflow or respective owner

Related posts about shell-scripting

Related posts about directory-listing