How to check if a directory has child directories?

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

Thanks - Dave

+6
source share
6 answers

Here is one way:

#!/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 
+10
source

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

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

If you want a script:

 find $DIR/* -type d 

gotta do the trick.

+3
source

Try this as a condition that you are testing:

 subdirs=$(ls -d $DIR/.*/ | grep -v "/./\|/../") 

subdirs will be empty if subdirectories

not,
+2
source

The solution is in pure bash, without any other program execution. This is not the most compact solution, but if it is executed in a loop, it can be more efficient, since the creation of a process is not required. If there are many files in '$dir' , the file extension may break.

 shopt -s dotglob # To include directories beginning by '.' in file expansion. nbdir=0 for f in $dir/* do if [ -d $f ] then nbdir=$((nbdir+1)) fi done if [ nbdir -gt 0 ] then echo "Subdirs" else echo "No-Subdirs" fi 
+2
source

Here's a more minimalist solution that will run the test on a single line.

 ls $DIR/*/ >/dev/null 2>&1 ; if [ $? == 0 ]; then echo Subdirs else echo No-subdirs fi 

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

+2
source

What about:

 num_child=`ls -al $DIR | grep -c -v ^d` 

If $ num_child> 2, you have child directories. If you do not need hidden directories, replace ls -al with ls -l.

 if [ $num_child -gt 2 ] then echo "$num_child child directories!" fi 
0
source

Source: https://habr.com/ru/post/893304/


All Articles