On 07/07/2025 at 07:02, Bernhard Voelker wrote:
On 7/6/25 13:11, Stefan Klinger wrote:
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.
IMHO, the number of tools required to implement such a simple test
should be 1, [...]
This "dir is empty" information is a quite volatile information and
can change in the next nano-second.
The question is what is the typical use case, i.e., the activity after
knowing the directory is empty?
If it's simply the deletion of the empty directory, then one can
directly try:
rmdir 'path/to/dir'
For other cases, I'd go with an already existing check
(though not specified by POSIX):
find -type d -empty
With that, testing for empty output is sufficient:
test "$(find 'path/to/dir' -type d -empty 2>/dev/null)" \
&& my-action
Have a nice day,
Berny
I've had this bash function for years:
is_empty () {
# get current status
IFS=$'\n' globstatus=($(shopt -p dotglob nullglob))
[ -d "$1" ] && {
shopt -s dotglob nullglob
local f=("$1"/*)
# return to original status
for i in ${globstatus[@]}; do eval "$i"; done
[ "${#f[@]}" -eq 0 ]
} || {
[ -f "$1" ] || return 1
[ -s "$1" ] && return 1 || return 0
}
}
--
Chris Elvidge
England