Empty directory cleanup

This script will remove all empty subdirectories within the directory supplied as a command line parameter.
i.e. ./CleanupDirs.sh /docs/stuff will remove any empty subdirectories of /docs/stuff.

#!/bin/bash
 
# This script was created by Dale Caon
# On the 15th of November, 2010
# for ANAT, the Australian Network for Art and Technology.
# Title : Empty Directory Cleanup Script.
# Description : This should be run to recursivly delete all empty subfolders in a directory.
# Requires : A posix compliant OS (or close). NOTE: Mac OSX does not count.
 
# Ensure that current working directory matches target dir
cd "$1"
if [ $? != 0 ];
then
        echo "Error: Failed to change directory - Exiting"
exit 1
fi
 
# find directories recursivly in current directory and output list within single quotes
# use sort to reverse order
# use xargs to convert sorted list to command line args for rmdir
# rmdir will error when removing non empty dirs therefore deleting empty dirs and leaving files intact.
 
find ./ -type d -printf "'%p'\n" | sort -r | xargs rmdir > /dev/null 2>&1

This took us ages to puzzle out so please make use of this.

This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *