Recursively delete empty directories
I recently had to find a neat way to remove all empty directories recursively on a Unix machine. In the world of UNIX you can expect to find a way to do things like this pretty easy. When I started to search for a neat way to do it (rather than reading a bunch of MAN-pages) I came across a really funny story on The Old New Thing. Windows users are so used to having to use an application to do simple things like this, they forget about scripting possibilities. Guess that will change with Power shell.
However this was about how to do this on Unix. Well, this is my solution:
#!/bin/sh
find $1 -type d | sort -r |
while read D
do
ls -l "$D" | grep -q 'total 0' && rmdir "$D" 2>/dev/null
done
That script takes one argument; a directory you want to remove if it and all its sub-directories are empty. Any directories encountered where files exists are preserved.
Comments
Anonymous
July 10, 2008
What if the directory is nonempty but contains only hidden files? Should that be an "ls -la" / total 2?Anonymous
July 11, 2008
The comment has been removedAnonymous
November 01, 2008
find <parent-dir> -depth -type d -empty -exec rmdir -v {} ;Anonymous
November 02, 2008
@ZungBang: Your example does not know because if I have a structure "A/B" where the folder B is the only content of A your example will only delete B. Also the -empty option is not available on all platforms, for example the standard find on Solaris 8 does not support -empty. Nor does the rmdir on Solaris 8 support "--ignore-fail-on-non-empty" which could be used to supress error messages (instead of piping to /dev/null) from rmdir.Anonymous
January 25, 2009
Here's a nice Perl one-liner: http://duramecho.com/ComputerPrograms/DeleteEmptyDirectories/index.htmlAnonymous
January 25, 2009
@Magnus: Nice since it does not print any error messages for non empty directories. However it assumes perl is installed which might not always be the case. Just in case the link disapears, here's the perl command: perl -MFile::Find -e"finddepth(sub{rmdir},'.')"Anonymous
February 13, 2009
@cellfish - no, ZungBang is correct - look up what the "-depth" option does to the recursion order.Anonymous
February 13, 2009
@cLive: fair enough but still all the options used are not available on all platforms.Anonymous
April 29, 2009
cellfish, your script saved my day but I suggest putting double quotes around $D otherwise the script will fail on directory names with spacesAnonymous
April 29, 2009
Good point! I've added double quotes in the original post now.