Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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 be able to run a script that will remove all my empty directories. The problem is some of them are nested, i.e. directories that only have empty directories in them, so the script needs to be recursive.

I know this:

find /media/server/data001/Unprotected/Downloads/ -type d -empty -exec rmdir {} \;

but I have no idea how to make it run again and again until all nested directories have been processed and then stop.

share|improve this question

What you need is depth-first traversal. With that, you'd start at the deepest directory and then move your way up. find has an option for that, so you can simply run:

find /some/path -depth -type d -exec rmdir {} \;

You may want to additionally suppress the warnings for non-empty directories. You can add 2>/dev/null at the end for that.

With GNU find (and others like the BSD find on OS X), you can optimize the command – and run it without warnings – using -empty, as you did above.

find /some/path -depth -type d -empty -exec rmdir {} \;
share|improve this answer

You must log in to answer this question.

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