Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
I think they're discussing something similar to this in this question too: – Tim Bielawa Nov 3 '10 at 19:47
up vote 2 down vote accepted

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.

share|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 posting your answer, you agree to the privacy policy and terms of service.

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