11

(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.

AndrewR
  • 442
  • 3
  • 10

3 Answers3

15

For all versions of find

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

If you have a newer version

 find -type d -empty -delete
Mike
  • 22,310
  • 7
  • 56
  • 79
  • cool, didn't know the `-delete` flag. – moestly May 18 '11 at 02: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 02: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 03:14
1

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)

AndrewR
  • 442
  • 3
  • 10
  • 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 04:06
0
for i in `find -type d -empty`; do rmdir $i; done
moestly
  • 1,188
  • 9
  • 11