user121196
user121196

Reputation: 31050

enumerate each sub directory in a directory in bash

for subdir in $( find $dir -type d ); do

    echo "subdir is $subdir"                                                                                                                            
done

the proble is that if the sub directory name contains space, they get separated, how do I resolve this?

Upvotes: 1

Views: 53

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84579

oldifs=$IFS
IFS=$'\n'
for subdir in $( find $dir -type d ); do
    echo "subdir is $subdir"
done
IFS=$oldifs

example:

$ bash dirnm.sh a
subdir is a
subdir is a/dir 1 
subdir is a/dir 2

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799102

for subdir in $somedir/*/ do
    echo "subdir is $subdir"                              
done

If you continue to have problems with spaces then you've goofed up your quoting elsewhere.

Upvotes: 0

anubhava
anubhava

Reputation: 785541

You can use process substitution:

while IFS= read -d '' -r subdir; do
    echo "subdir is $subdir"                                                                                                                            
done < <(find "$dir" -type d -print0)

Upvotes: 1

Related Questions