How do I tell if a directory is empty?

To see if a directory is has anything in it, I do this:

if [ -n "$(ls /some/dir 2>/dev/null)" ]; then
    # do something
fi

But surely there is a more easy-to-read and elegant way. Isn't there?

I think that you found a good solution to your problem. But there is a small bug: ls must be called wirth -A option.

is_file()
{
    for f
    do
        [ -f "$f" ] && return;
    done
    return 1
}

if is_file /some/dir/*
then
   : do whatever
fi



##

The -A option to ls is not standard.

OK, cfajohnson, your solution works. But it requires a whole additional separate function. The bigness wipes out any improvement in elegance or readability.

I kept looking at the stat command, thinking surely there must be an option that reports how many entries a directory has or something I could figure out to mean that. For example, this returns the number of blocks allocated, but that's not helpful for what I want at all.

stat -c%b /some/dir
stat -c%h /some/dir

could do the trick, as it returns '2' for empty directories, but it apparently only counts normal files and directories.

No, I think that returns hard links to the directory itself, not hard links in the directory. I just created a directory and tried it and it returns 2 whether the directory is empty or has some test files in it.

Thanks for looking though. Maybe my original solution isn't so bad.