I was looking for a way to check whether a directory was empty and came across
this page.... too many options - what would anyone suggest?
Many of the options discussed there are outright wrong, unsafe, or insane. Unfortunately, there is no ideal option.
I thought there may be some simple option like: "if [ ! -x "$1" ]; then"
Unfortunately, there is no single-character option in the
test
command that does this. One might think that the "-s" option (which tests for zero-size / non-zero-size) should work, but it doesn't.
but I don't know the name of this construct so can't look at a manpage for it...
SirDice's advice is the easiest option to look it up. But it is not 100% correct. If you say "if [...]" in the shell, traditionally that ran the
[
executable (no joke, there is an executable whose name is a single opening square bracket), which was identical to the
test
command, which has a man page like SirDice said. However, modern shells (definitely true for bash, probably also true for tcsh) no longer run the external command for these statements, and instead use a built-in implementation of test. The good news is that the built-in versions are probably supersets of the test command ... but probably isn't certainty. The other good news is that the man pages for the shell do document the built-in versions of the test. The bad news is that the man pages for bash and tcsh are so insanely long that finding the test in there takes a lot of patience. If I had nothing useful to do, I could look up the Posix standard, but I have a day job.
OK, now finally a useful suggestion. I don't know an easy way to do it within the shell. But the
find
command has a simple option to check whether a directory is empty. So here is something that works: Run "find directory_name -type d -prune -empty". It will return the directory name if that directory is empty, and will return nothing if there is something in that directory. Because of the "-prune" option in it, it is both correct, and reasonably efficient. I don't even know whether better efficiency is possible in general; the implementation of how directories work is file-system specific, and many file systems store deleted entries in a directory block, so a length check is not always correct.