How do I check if a directory has child directories?

Viewed 18504

Using bash, how do I write an if statement that checks if a certain directory, stored in the a script variable named "$DIR", contains child directories that are not "." or ".."?

Thanks, - Dave

9 Answers

in my case it doesn't work as @AIG wrote - for empty dir I got subdircount=1 (find returns only dir itself).

what works for me:

#!/usr/bin/bash
subdircount=`find /d/temp/ -maxdepth 1 -type d | wc -l`
if [ $subdircount -ge 2 ]
then
    echo "not empty"
else
    echo "empty"
fi

I'd like to know if a directory has any subdirectories. For this purpose I don't need recursion, and I don't care what they are. So:

(find -L . -mindepth 1 -maxdepth 1 -type d | wc -l)

Here is the best answer you will ever see on this issue.

function hasDirs ()
{
    declare $targetDir="$1"    # Where targetDir ends in a forward slash /
    ls -ld ${targetDir}*/
}

If you are already in the target directory:

if hasDirs ./
then

fi

If you want to know about another directory:

if hasDirs /var/local/   # Notice the ending slash
then

fi
Related