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

前端 未结 10 1570
感情败类
感情败类 2020-11-28 02:29

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
10条回答
  •  再見小時候
    2020-11-28 02:57

    Here's another way of listing files inside a directory (using a different tool, not as efficient as some of the other answers).

    cd "search_dir"
    for [ z in `echo *` ]; do
        echo "$z"
    done
    

    echo * Outputs all files of the current directory. The for loop iterates over each file name and prints to stdout.

    Additionally, If looking for directories inside the directory then place this inside the for loop:

    if [ test -d $z ]; then
        echo "$z is a directory"
    fi
    

    test -d checks if the file is a directory.

提交回复
热议问题