0

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?

1

1 Answer 1

2

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

2
  • 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, 2010 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. Nov 3, 2010 at 20:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .