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

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

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.


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 with find . -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.

| improve this answer | |
  • This is exactly what I was looking for. find . -depth -type d -empty -delete worked for me as expected. Will definitly remember that -depth parameter for other uses. Thanks – skinp Nov 3 '10 at 20:09
  • I.e., even if find . -type d -empty doesn't return foo adding -delete does work. It checks if foo is empty after it has deleted bar and bar1 and thus it would delete foo. – Mark Wagner Nov 3 '10 at 20:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.