How do you remove nested empty directories using a Bash script on Linux?

3

2

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.

dave

Posted 2013-05-19T11:12:13.103

Reputation: 31

Answers

11

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

slhck

Posted 2013-05-19T11:12:13.103

Reputation: 182 472