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

前端 未结 10 2113
情歌与酒
情歌与酒 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: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.

提交回复
热议问题