tags:

views:

208

answers:

4

I an writing a script in Linux and need to go over all subdirectories names in a given directory. How can i loop these directories (and skip regular files).

For example, the given directory is /tmp/ and has the following subdirectories: /tmp/A, /tmp/B, /tmp/C I want to retrieve A,B,C.

+2  A: 

find . -type d -maxdepth 1

Anonymous
this answer is good, except that i receive the full paths, while i want only the names of the directories.
Erik Sapir
+5  A: 
cd /tmp
find . -maxdepth 1 -mindepth 1 -type d -exec basename '{}' \;

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

  • -exec basename '{}' \; calls basename for every result, hence stripping any leading ./

E voila!

Boldewyn
great answer! thanks
Erik Sapir
you should accept the answer if it completely solves your problem - that's good stackoverflowiquette.
ammoQ
I am new here, and don't have enough reputation to vote
Erik Sapir
By the way: Note, that all answers will find hidden folders, too (that is, folders starting with a dot)! If you don't want this, add ` -regex '\./[^\.].*'` before the printf or exec options.
Boldewyn
You don't need rep to accept an answer. It's the grey-bordered hook in the upper left of each answer (of your questions). Actually, you'll get 2 rep from accepting ;-)
Boldewyn
+1  A: 
find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"
Ignacio Vazquez-Abrams
That's nice too and eliminates the need for `basename`. I would prefer this over my answer.
Boldewyn
+2  A: 

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

for dir in /tmp/*/
do
    dir=${dir%*/}
    echo ${dir##*/}
done
ghostdog74
Well, yes, 'find' is kind of the Swiss Army knife on *NIX machines to find something file related. But a pure version with bash builtins only is good to know, too. +1
Boldewyn