Looping over directories in Bash

前端 未结 3 1630
天命终不由人
天命终不由人 2020-12-09 10:24

I have a fundamental question about how bash works, and a related practical question.

Fundamental question: suppose I am in a directory that has three subdirectories

3条回答
  •  抹茶落季
    2020-12-09 10:53

    This should work:

    shopt -s nullglob   # empty directory will return empty list
    for dir in ./*/;do
        echo "$dir"         # dir is directory only because of the / after *
    done
    

    To be recursive in subdirectories too, use globstar:

    shopt -s globstar nullglob
    for dir in ./**/;do
        echo "$dir" # dir is directory only because of the / after **
    done
    

    You can make @Adrian Frühwirths' method to be recursive to sub-directories by using globstar too:

    shopt -s globstar
    for dir in ./**;do
        [[ ! -d $dir ]] && continue # if not directory then skip
        echo "$dir"
    done
    

    From Bash Manual:

    globstar

    If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

    nullglob

    If set, Bash allows filename patterns which match no files to expand to a null string, rather than themselves.

提交回复
热议问题