From a shell script, how do I check if a directory contains files?
Something similar to this
if [ -e /some/dir/* ]; then echo "huzzah"; fi;
but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).
Mixing prune things and last answers, I got to
that works for paths with spaces too
Try:
I am surprised the wooledge guide on empty directories hasn't been mentioned. This guide, and all of wooledge really, is a must read for shell type questions.
Of note from that page:
I dislike the
ls - A
solutions posted. Most likely you wish to test if the directory is empty because you don't wish to delete it. The following does that. If however you just wish to log an empty file, surely deleting and recreating it is quicker then listing possibly infinite files?This should work...
Assume you don't have a file named
*
into/any/dir/you/check
, it should work onbash
dash
posh
busybox sh
andzsh
but (for zsh) requireunsetopt nomatch
.Performances should be comparable to any
ls
which use*
(glob), I guess will be slow on directories with many nodes (my/usr/bin
with 3000+ files went not that slow), will use at least memory enough to allocate all dirs/filenames (and more) as they are all passed (resolved) to the function as arguments, some shell probably have limits on number of arguments and/or length of arguments.A portable fast O(1) zero resources way to check if a directory is empty would be nice to have.
update
The version above doesn't account for hidden files/dirs, in case some more test is required, like the
is_empty
from Rich’s sh (POSIX shell) tricks:But, instead, I'm thinking about something like this:
Some concern about trailing slashes differences from the argument and the find output when the dir is empty, and trailing newlines (but this should be easy to handle), sadly on my
busybox
sh
show what is probably a bug on thefind -> dd
pipe with the output truncated randomically (if I usedcat
the output is always the same, seems to bedd
with the argumentcount
).