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

Jonathan I. Kamens jik at athena.mit.edu
Thu Apr 4 00:21:50 AEST 1991


In article <1991Mar30.225406.20493 at dg-rtp.dg.com>, hunt at dg-rtp.rtp.dg.com (Greg Hunt) writes:
|> 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.

  Um, I can't imagine this being true for *any* remotely normal flavor of Unix.

  I just did the following tests on both a BSD-derived and a SysV-derived
system:

  1) Create a new, empty directory.  Check its size.  Cd into it and run the
following:

	if [ -s . ]; then
		echo "Directory has some files in it."
	else
		echo "Directory is empty."
	fi

and see what happens.

  2) Create a bunch of files in the directory.  Remove them all.  Check the
directory's size again.

  In the first case, the size of the newly created directory was non-zero,
just as I expected, and the if statement printed out "Directory has some files
in it," although I hadn't added any.  How can the directory be empty when it
has to store entries for "." and ".." in it?

  In the second case, the directory did not shrink when the files were
deleted.  Directories grow.  I'm not even convinced that fsck shrinks empty
dirctories; I believe the only way to shrink a directory with lots of empty
entries in it is to create a new directory, mv the files from the old
directory into the one one, and remove the old directory.

  If you tried what you posted on a system and it worked, I'd be very
interested in knowing what kind of Unix it was and what type of filesystem
it's running.  Does it store the "." and ".." directory entries somewhere
special, or does it fake them without putting them in the filesystem, or does
"size" mean something special in the context of directories, or what?

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710



More information about the Comp.unix.questions mailing list