Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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
add comment

Your Answer

 
discard

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.