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

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

    $ pwd; ls -l
    /home/victoria/test
    total 12
    -rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  a
    -rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  b
    -rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  c
    -rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'c d'
    -rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  d
    drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_a
    drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_b
    -rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'e; f'
    
    $ find . -type f
    ./c
    ./b
    ./a
    ./d
    ./c d
    ./e; f
    
    $ find . -type f | sed 's/^\.\///g' | sort
    a
    b
    c
    c d
    d
    e; f
    
    $ find . -type f | sed 's/^\.\///g' | sort > tmp
    
    $ cat tmp
    a
    b
    c
    c d
    d
    e; f
    

    Variations

    $ pwd
    /home/victoria
    
    $ find $(pwd) -maxdepth 1 -type f -not -path '*/\.*' | sort
    /home/victoria/new
    /home/victoria/new1
    /home/victoria/new2
    /home/victoria/new3
    /home/victoria/new3.md
    /home/victoria/new.md
    /home/victoria/package.json
    /home/victoria/Untitled Document 1
    /home/victoria/Untitled Document 2
    
    $ find . -maxdepth 1 -type f -not -path '*/\.*' | sed 's/^\.\///g' | sort
    new
    new1
    new2
    new3
    new3.md
    new.md
    package.json
    Untitled Document 1
    Untitled Document 2
    

    Notes:

    • . : current folder
    • remove -maxdepth 1 to search recursively
    • -type f : find files, not directories (d)
    • -not -path '*/\.*' : do not return .hidden_files
    • sed 's/^\.\///g' : remove the prepended ./ from the result list

提交回复
热议问题