I want to delete the top level directory which does not contain any files, but can contain other empty (meaning again not containing files) directories. For example:
$ ls -R
.: foo/
./foo/: bar bar1
./foo/bar/:
./foo/bar1/:
Here, I would like to delete the directory foo/
(and its subdirectories).
At first, I thought of using something like find . -type d -empty
for the search, but since foo contains directories, it only finds the lower level ones:
$ find . -type d -empty
./foo/bar
./foo/bar1
I guess I could loop until find . -type d -empty
finds nothing, but I may end up having a very big directory structure containing a lot of those empty directories and I'm concerned about the performance impact of doing it that way...
Any idea?
find . -depth -type d -empty
should do the trick.-depth
will cause find to process a directory's contents before the directory itself.Edit:
Presumably you'd be using something like
-delete
at the end of this find, else you'd have the same problem you described. Also worth noting,-delete
actually implies-depth
, so really, sticking withfind . -type d -empty -delete
would give you what you're looking for in one pass; presuming you have no problem deleting any other lower level empty directories you encounter as well.