Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a directory has child directories?

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

like image 280
Dave Avatar asked Jul 21 '11 18:07

Dave


People also ask

How many parent directory is allowed for a child directory?

A directory in the filesystem tree may have many children, but it can only have one parent.

How do I find the directory of a script?

pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0 , so dirname $0 should give you the directory of the current script).


2 Answers

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
like image 102
AlG Avatar answered Sep 17 '22 23:09

AlG


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).

like image 31
robert Avatar answered Sep 18 '22 23:09

robert