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
A directory in the filesystem tree may have many children, but it can only have one parent.
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).
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With