I am looking for a way to use the find command to tell if a folder has no files in it. I have tried using the -empty
flag, but since I am on macOS the system files the OS places in the directory such as .DS_Store
cause find to not consider the directory empty. I have tried telling find to ignore .DS_Store
but it still considers the directory not empty because that file is present.
Is there a way to have find exclude certain files from what it considers -empty
? Also is there a way to have find return a list of directories with no visible files?
The -empty
predicate is rather simple, it's true for a directory if it has any entries other than .
or ..
.
Kind of an ugly solution, but you can use -exec
to run another find
in each directory which will implement your criteria for deciding what directories you want to include.
Below:
find
will execute sh -c
for each directory in /starting/point
sh
will execute another find
with different criteria.find
will print the first match and then quitread
will consume the output (if any) of the inner find
. read
will have an exit status of 0 only if the inner find
printed at least one line, non-zero otherwisefind
, the outer find
's -exec
predicate will evaluate to false-exec
is followed by -o
, the following -print
action will be executed only for those directories which do not match the inner find
's criteriafind /starting/point \
-type d \( \
-exec sh -c \
'find "$1" -mindepth 1 -maxdepth 1 ! -name ".*" -print -quit | read' \
sh {} \; \
-o -print \
\)