Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

(on a Linux system)

I have a large set of nested subdirectories on a filesystem. I would like to prune all directory paths that contain no files at all.

In other words I would like to delete every directory where there are no files in that directory or in any subdirectory of that directory recursively.

share|improve this question
up vote 15 down vote accepted

For all versions of find

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

If you have a newer version

 find -type d -empty -delete
share|improve this answer
cool, didn't know the -delete flag. – ansi_lumen May 18 '11 at 2:21
Me neither. I learned something new. I've written scripts before, using recursion to find empty directories. This greatly simplifies that task. – James May 18 '11 at 2:29
ya the -empty flag really helps out here. It also works to find empty files if you didn't include the -type d or just used -type f – Mike May 18 '11 at 3:14

May not be the best solution, but this script works:


while true
    DIRS=`find . -xdev -type d -exec find {}  -maxdepth 0 -empty  \;`
    if [ -z "$DIRS" ]; then
        exit 0
        echo $DIRS | xargs rmdir

(based partly on the answer to List all empty folders)

share|improve this answer
Just occurred to me that this will go into an infinite loop if you don't have permission to remove any of the empty directories, so please use the accepted answer instead :) – AndrewR May 19 '11 at 4:06
for i in `find -type d -empty`; do rmdir $i; done
share|improve this answer
Close, but no cigar. You are missing the case where removing a directory causes its parent to become empty. – Simon Richter May 18 '11 at 6:36
That's true. I would find them in a second run. Never had this case in real live. – ansi_lumen May 18 '11 at 11:21

Your Answer


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.