How to loop over directories in Linux?


Question

I am writing a script in bash on Linux and need to go through all subdirectory names in a given directory. How can I loop through these directories (and skip regular files)?

For example:
the given directory is /tmp/
it has the following subdirectories: /tmp/A, /tmp/B, /tmp/C

I want to retrieve A, B, C.

1
143
12/24/2013 1:32:51 AM

Accepted Answer

cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'

A short explanation: find finds files (quite obviously)

  • . is the current directory, after the cd it's /tmp (IMHO this is more flexible than having /tmp directly in the find command. You have only one place, the cd, to change, if you want more actions to take place in this folder)

  • -maxdepth 1 and -mindepth 1 make sure, that find really, only looks in the current dir and doesn't include '.' in the result

  • -type d looks only for directories

  • -printf '%f\n prints only the found folder's name (plus a newline) for each hit.

E voila!

119
8/26/2013 2:52:59 PM

All answers so far use find, so here's one with just the shell. No need for external tools in your case:

for dir in /tmp/*/     # list directories in the form "/tmp/dirname/"
do
    dir=${dir%*/}      # remove the trailing "/"
    echo ${dir##*/}    # print everything after the final "/"
done

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon