For any directory other than the current one, you can check if it's empty by trying to rmdir
it, because rmdir
is guaranteed to fail for non-empty directories. If rmdir
succeeds, and you actually wanted the empty directory to survive the test, just mkdir
it again.
Don't use this hack if there are other processes that might become discombobulated by a directory they know about briefly ceasing to exist.
If rmdir
won't work for you, and you might be testing directories that could potentially contain large numbers of files, any solution relying on shell globbing could get slow and/or run into command line length limits. Probably better to use find
in that case. Fastest find
solution I can think of goes like
is_empty() {
test -z $(find "$1" -mindepth 1 -printf X -quit)
}
This works for the GNU and BSD versions of find
but not for the Solaris one, which is missing every single one of those find
operators. Love your work, Oracle.
related: https://stackoverflow.com/q/91368/52074
– Trevor Boyd Smith – 2019-02-12T19:36:13.550