Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

(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
add comment

3 Answers

up vote 13 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
2  
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
add comment
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
add comment

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

#!/bin/sh

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

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

share|improve this answer
1  
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
add comment

Your Answer

 
discard

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.