LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   How to check if a directory is empty? (https://www.linuxquestions.org/questions/linux-software-2/how-to-check-if-a-directory-is-empty-235857/)

Aziz 09-27-2004 01:34 PM

How to check if a directory is empty?
 
Hi guys I just went throught this site by luck.. seems very nice and hope I will learn alot from it..

I am trying to write a script for my first class, part of it to check is if a directory is empty or not.. I am doing it in bash/korn

I tried many things like:

#$d is the directory name

if [[ ls $d ]] > /dev/null
then
echo "not empty"
else
echo "empty"
fi

I also tried if [[ -f $d/*.* ]]

which also didnt work

I would appreciate any help

peace,

foo_bar_foo 09-27-2004 03:01 PM

if [ -z `ls /some/dir` ]

wipe 09-27-2004 04:46 PM

That won't work properly, it produces an error if there is more than one file in the directory. Also, hidden files are missed. A suggestion:
Code:

if [ -z "`ls -A $d`" ]; then
    echo empty
else
    echo not empty
fi

The [[ ]] command seems to be rarely used (at least in Bash). It can do string matching with the normal pathname expansion patterns that resemble primitive regular expressions. The [ ] command is more useful. Proper regular expressions can be handled with grep and sed, for example.

Here's a good Bash guide:
http://www.tldp.org/LDP/abs/html/index.html

Regards
Simon


All times are GMT -5. The time now is 11:40 AM.