Deleting empty directories using find

Hello, I'm submitting this thread, because I was looking a way to delete empty directories using find and I found a thread from 2007 that helped me. I have worked from that threat, but I found that the command sent would analyze original directory and may delete it to. I have come up with expanded find command so parent directory would no be analyzed and would no put it on risk of being delete. The main problem with this command is that child directories MUST not have the same name as parent directory.

This is the initial directory setup

> ls -R a
a:
total 8
w/
x/
y/
z/

a/w:
total 0
w.txt

a/x:
total 0
x.txt

a/y:
total 0
y.txt

a/z:
total 0

Now running the following Solaris command you may delete the "z" directory without putting in risk your "a" directory.

> find a  \( -name a -prune \) -o -depth -type d -exec echo Analize {} \; -exec rmdir {} 2>/dev/null \;
Analize a/w
Analize a/x
Analize a/y
Analize a/z

The result of the command would be like these:

> ls -R a
a:
total 6
w/
x/
y/

a/w:
total 0
w.txt

a/x:
total 0
x.txt

a/y:
total 0
y.txt

Please notice that "a/z" directory is no longer present and that "a" directory was not analyzed.

You may delete "-exec echo..." from the command line and it will produce same result, that part was just to demonstrate operation of the command.

My best regard and I hope this would be of help to some one.

I hope it's OK, but I've changed the subject title to remove the "in Solaris" part, because I think this should work on just about any UNIX.

Thanks for sharing :slight_smile:

To delete empty directories under/top/level/dir using find:

find /top/level/dir/* -type d | xargs rmdir

Every day you learn something new. I would like to write a better command with the suggestion from jpradley. thanks for you suggestion. Using xargs is good you would only need to redirect standar error to /dev/null so you would not have the error message.

So having the initial directory structure from my first post I would re-write the command as:

> find a/* -type d -exec echo Analize {} \; -exec rmdir {} 2> /dev/null \;

This will produce the same result as spected and would not analize parent directory.

Againg thanks jpradley.