Shell Directory – How to Remove Empty Directory Trees Without Deleting Files

directoryrmshell

Suppose I have a dir tree like this:

ROOTDIR
    └--SUBDIR1
        └----SUBDIR2
            └----SUBDIR3

I am looking for a command such that when I input:

$ [unknown command] ROOTDIR

The whole dir tree can be deleted if there is no file but only dirs inside the whole tree. However, say if there is a file called hello.pdf under SUBDIR1:

ROOTDIR
    └--SUBDIR1
        └--hello.pdf
        └----SUBDIR2
            └----SUBDIR3

Then the command must only delete SUBDIR2 and below.

Best Answer

Alexis is close. What you need to do is this:

find . -type d -depth -empty -exec rmdir "{}" \;

That will first drill down the directory tree until it finds the first empty directory, then delete it. Thus making the parent directory empty which will then be deleted, etc. This will produce the desired effect (I do this probably 10 times a week, so I'm pretty sure it's right). :-)

Related Question