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

前端 未结 10 1512
感情败类
感情败类 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

    The other answers on here are great and answer your question, but this is the top google result for "bash get list of files in directory", (which I was looking for to save a list of files) so I thought I would post an answer to that problem:

    ls $search_path > filename.txt
    

    If you want only a certain type (e.g. any .txt files):

    ls $search_path | grep *.txt > filename.txt
    

    Note that $search_path is optional; ls > filename.txt will do the current directory.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 03:01

    On the Linux version I work with (x86_64 GNU/Linux) following works:

    for entry in "$search_dir"/*
    do
      echo "$entry"
    done
    
    0 讨论(0)
  • 2020-11-28 03:02
    for entry in "$search_dir"/*
    do
      echo "$entry"
    done
    
    0 讨论(0)
  • 2020-11-28 03:05

    The accepted answer will not return files prefix with a . To do that use

    for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
    do
      echo "$entry"
    done
    
    0 讨论(0)
  • 2020-11-28 03:05

    Just enter this simple command:

    ls -d */
    
    0 讨论(0)
提交回复
热议问题