How to recursively list subdirectories in Bash without using “find” or “ls” commands?

前端 未结 10 2039
情歌与酒
情歌与酒 2020-12-01 17:22

I know you can use the find command for this simple job, but I got an assignment not to use find or ls and do the job. How can I do th

相关标签:
10条回答
  • 2020-12-01 17:47

    Try using

    tree -d
    
    0 讨论(0)
  • 2020-12-01 17:48

    The du command will list subdirectories recursively.

    I'm not sure if empty directories get a mention, though

    0 讨论(0)
  • 2020-12-01 17:49

    Based on this answer; use shell options for the desired globbing behaviour:

    • enable ** with globstar (Bash 4.0 or newer)
    • include hidden directories with dotglob
    • expand to the empty string instead of **/*/ if there is no match with nullglob

    and then use printf with the %q formatting directive to quote directory names with special characters in them:

    shopt -s globstar dotglob nullglob
    printf '%q\n' **/*/
    

    so if you have directories like has space or even containing a newline, you'd get output like

    $ printf '%q\n' **/*/
    $'has\nnewline/'
    has\ space/
    

    with one directory per line.

    0 讨论(0)
  • 2020-12-01 17:51

    Technically, neither find nor ls are used by find2perl|perl or File::Find directly.

    $ find2perl -type d | perl
    $ perl -MFile::Find -e'find(sub{-d&&print"$File::Find::name\n"},".")'
    
    0 讨论(0)
提交回复
热议问题