Tue Sep 29 19:10:34 PDT 2015

Removing Empty Directories

I have been surprised sometimes to see how much disk space empty directories consume. I suppose that this depends on the file system that you are using, but nevertheless sometimes it is convenient to find and potentially remove empty directories. (I seem to find that empty directories on Windows are particularly disk space usage heavy).

Here is a script which accomplishes this using the find command. I am including the author's name - I think I tweaked the script slightly at some point to report what it was going to do, rather than actually doing it. If you want it to remove empty directories change the DOIT variable to "y". Actually the rmdir command will only remove an actually empty directory, so the script is fairly safe. However, use at your own risk, as always.

#!/bin/sh -f
# rmemptydir - remove empty directories
# Heiner Steven (heiner.steven@odn.de), 2000-07-17
# Category: File Utilities


[ $# -lt 1 ] && set -- .

find "$@" -depth -type d -print |
    while read dir
        [ `ls -a "$dir" | wc -l` -lt 3 ] || continue
        echo >&2 "$0: removing empty directory: $dir"
        if [ $DOIT = "y" ]
          rmdir "$dir" || exit $?
exit 0

Comments are closed

If you would like to get in touch with me, please mail zfs at themolecularuniverse.com

recent comments

Posted by ZFS | Permanent link | File under: bash
[StumbleUpon] [Digg] [Reddit] [Facebook] [Google]