Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a folder with some directories and some files.

for d in *; do
 echo $d
done

will loop through all files, but I want to loop only through directories. How do I do that?

share|improve this question

3 Answers

up vote 10 down vote accepted

You can specify a slash at the end to match only directories:

for d in */ ; do
    echo "$d"
done
share|improve this answer
2  
Note that it also includes symlinks to directories. – Stephane Chazelas Aug 14 at 16:09
so how would you exclude symlinks then? – rubo77 Aug 14 at 22:55
1  
@rubo77: You can test with [[ -L $d ]] whether $d is a symbolic link. – choroba Aug 14 at 23:00

You can test with -d:

for f in *; do
    if [[ -d $f ]]; then
        # $f is a directory
    fi
done

This is one of the file test operators.

share|improve this answer
1  
Note that it will include symlinks to directories. – Stephane Chazelas Aug 14 at 16:12

You can use pure bash for that, but it's better to use find:

find . -maxdepth 1 -type d -exec echo {} \;

(find additionally will include hidden directories)

share|improve this answer
3  
Note that it doesn't include symlinks to directories. You can use shopt -s dotglob for bash to include hidden directories. Yours will also include .. Also note that -maxdepth is not a standard option (-prune is). – Stephane Chazelas Aug 14 at 16:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.