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.
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!
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