How do I check if a directory has child directories?

Here's a more minimalist solution that will perform the test in a single line..

ls $DIR/*/ >/dev/null 2>&1 ; 

if [ $? == 0 ]; 
then 
  echo Subdirs
else 
  echo No-subdirs
fi

By putting / after the * wildcard you select only directories, so if there is no directories then ls returns error-status 2 and prints the message ls: cannot access <dir>/*/: No such file or directory. The 2>&1 captures stderr and pipes it into stdout and then the whole lot gets piped to null (which gets rid of the regular ls output too, when there is files).


As the comments have pointed out, things have changed in the last 9 years! The dot dirs are no longer returned as part of find and instead the directory specified in the find command is.

So, if you want to stay with this approach:

#!/bin/bash
subdircount=$(find /tmp/test -maxdepth 1 -type d | wc -l)

if [[ "$subdircount" -eq 1 ]]
then
    echo "none of interest"
else
    echo "something is in there"
fi

(originally accepted answer from 2011)

#!/usr/bin/bash
subdircount=`find /d/temp/ -maxdepth 1 -type d | wc -l`

if [ $subdircount -eq 2 ]
then
    echo "none of interest"
else
    echo "something is in there"
fi

I'm not really sure what you trying to do here, but you can use find:

find /path/to/root/directory -type d

If you want to script it:

find $DIR/* -type d

should do the trick.