I would like to clean up some folders. So I want to delete all folders which are empty or only contain other folders...

First I tried

find . -type d -delete

but this lists the subfolders after the parents, so I would have to execute it multiple times.

So I tried using tac and pipes

find . -type d | tac | xargs rmdir

This one fails on whitespaces, etc, so I need a masking - now I am stuck...

  • 5
    Possible duplicate: How to remove all empty directories in a subtree? – Marco Nov 6 '15 at 10:37
  • Nope. I want also to remove non-empty folder, which contain only folders! – Jaster Nov 6 '15 at 11:04
  • The -depth option will do what you want... – Jeff Schaller Nov 6 '15 at 11:07
  • multiple times? how often?... thats why I want to do it recursive – Jaster Nov 6 '15 at 11:09
  • 2
    At least in GNU 'find', the -delete action also implies -depth i.e. directories containing only other directories become empty as the command executes from the bottom of the tree up. – steeldriver Nov 6 '15 at 11:10
find . -type d -depth -exec rmdir {} +

should work if you have a halfway recent find(1) - note that execplus was added in 1989 ;-)

Note that there was a hint that there may be non-standard find implementations that emit a warning when -depth was not specified as the first primary.

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