How to loop over directories in Linux?
cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n'
A short explanation:
find
finds files (quite obviously).
is the current directory, which after thecd
is/tmp
(IMHO this is more flexible than having/tmp
directly in thefind
command. You have only one place, thecd
, to change, if you want more actions to take place in this folder)-maxdepth 1
and-mindepth 1
make sure thatfind
only looks in the current directory and doesn't include.
itself 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.
Et voilà!
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