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.


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 {} \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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