How do I loop through only directories in bash?

  • I have a folder with some directories and some files (some are hidden, beginning with dot).

    for d in *; do
     echo $d
    done
    

    will loop through all files, but I want to loop only through directories. How do I do that?

  • rubo77

    rubo77 Correct answer

    7 years ago

    If you need to select more specific files than only directories use find and pass it to while read:

    shopt -s dotglob
    find * -prune -type d | while IFS= read -r d; do 
        echo "$d"
    done
    

    Use shopt -u dotglob to exclude hidden directories (or setopt dotglob/unsetopt dotglob in zsh).

    IFS= to avoid splitting filenames containing one of the $IFS, for example: 'a b'

    see AsymLabs answer below for more find options


    edit:
    In case you need to create an exit value from within the while loop, you can circumvent the extra subshell by this trick:

    while IFS= read -r d; do 
        if [ "$d" == "something" ]; then exit 1; fi
    done < <(find * -prune -type d)
    

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM