On 7/6/25 06:11, Stefan Klinger wrote:
Hello,

I've implemented a small tool [1] to test whether a directory is
empty, and I think it would make a useful addition to GNU coreutils.

mkdir sub
[ -d sub -a -z "$(ls -A sub)" ] && echo boom

Is it a directory, is it empty.

(Admittedly I didn't check that we can ACCESS its contents, but returning "I don't know" wasn't in the mandate. The first part could instead be -d sub/. if you want that "maybe" to be answered as "no". :)

IMHO, the number of tools required to implement such a simple test
should be 1, but proposed solutions typically involve an invocation of
`ls` or `find` and subsequent output processing by `test` or `wc`.
These solutions tend to accumulate a degree of complexity that I
personally find unsatisfying for the task at hand.

Do you also need a specific tool to check if a file is zero length? Because "touch file; [ -f file -a 0 -eq "$(stat -c%s file)" ] && echo boom" is a similar level of complexity, since merely going stat -c%s file doesn't prove that file exits and isn't a directory...

Some solutions are more compact and use only shell builtins, e.g.,

     $ if ! (shopt -s failglob dotglob; : *) 2>/dev/null; then
           echo is empty
       fi

but this may not port nicely to other shells (and has some other
caveats).

Reasonably sure the seemingly obvious thing above is posix.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html

I have built `isemptydir` according to my own needs and standards,
which may not line up with the culture at GNU/coreutils.

I'm philosophically fairly anti-gnu (in that I think they're often doing it wrong), but I maintain toybox (android's command line utilities), used to maintain busybox (Linksys through Alpine's command line utilities), and have been subscribed to the austin group (posix committee) mailing list for many years and dialed into more than one meeting. (Honestly, we all get it wrong a lot...)

But given that Unix is 56 years old and Linux is 34, you'd think if this tool was needed it would have shown up by now.

It's possible there's a security race where "open filehandle, fstat(filehandle) to confirm it's a directory and no other user can write to it, readdir(filehandle) to see that no other files are in it, openat(filehandle, blah) to create new file" is sometimes needed to avoid things changing out from under us between the test -d and $(ls)...

But your isemptydir command exiting before the information can be used kinda obviates that.

Rob

Reply via email to