How do I tell when a directory is empty in a script?

Greg Hunt hunt at dg-rtp.rtp.dg.com
Sun Mar 31 08:54:06 AEST 1991


In article <1991Mar30.040400.13893 at ncsu.edu>, harris at catt.ncsu.edu (Michael Harris) writes:
> When I am running a shell script, how can I tell when a directory is empty?
> I tried looking at the output of ls -a but it includes . and ..
> Suggestions anyone?

If the only files that are shown by an "ls -la" of a directory are
"." and "..", then the directory is "empty".  The "." file is just a
shorthand way of saying "the current directory", so it refers to the
directory itself.  The ".." file is a shorthand way of saying "the
parent directory of this directory", so it refers to the superior
directory.  If you look closely at an "ls -lia" listing, you'll notice
that the "." and ".." files are really hard links to the current
directory and the parent directory, respectively.

All directories are automatically created with the "." and ".." files
in them, and you cannot remove those files yourself.  They will be
deleted when the directory itself is deleted.

Once ls shows that "." and ".." are the only files remaining in a
directory, then you can delete the directory using the rmdir command.

Telling whether a directory is empty from a script should be possible
by looking at the size of the directory itself.  If the directory size
is zero, then the directory is empty.  Otherwise, it contains some
files.  You should check this out on your system to make sure it holds
true for the flavor of UNIX that you're using.

If it does then you can see if a directory is empty this way (using
the Bourne shell):

if [ -d file ] ; then
    echo "File is a directory and exists"

    if [ -s file ] ; then
        echo "Directory has some files in it"
    else
        echo "Directory is empty"
    fi
else
    if [ -f file ] ; then
        echo "File is a regular file and exists"
    else
        echo "File does not exist"
    fi
fi

The "-d file" is a test that returns true (zero) if the file exists
and is a directory.

The "-s file" test returns true if the file exists and has a size
greater than zero.

The "-f file" test returns true if the file exists and is a regular
file.

Look at the man pages for test or sh to see what other tests you can
use as conditions inside if's, etc.

Enjoy!

-- 
Greg Hunt                        Internet: hunt at dg-rtp.rtp.dg.com
DG/UX Kernel Development         UUCP:     {world}!mcnc!rti!dg-rtp!hunt
Data General Corporation
Research Triangle Park, NC, USA  These opinions are mine, not DG's.



More information about the Comp.unix.questions mailing list