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

前端 未结 10 1557
感情败类
感情败类 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 03:15

    This is a way to do it where the syntax is simpler for me to understand:

    yourfilenames=`ls ./*.txt`
    for eachfile in $yourfilenames
    do
       echo $eachfile
    done
    

    ./ is the current working directory but could be replaced with any path
    *.txt returns anything.txt
    You can check what will be listed easily by typing the ls command straight into the terminal.

    Basically, you create a variable yourfilenames containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variable eachfile that contains a single element of the variable it's looping through, in this case a filename. This isn't necessarily better than the other answers, but I find it intuitive because I'm already familiar with the ls command and the for loop syntax.

提交回复
热议问题