Bash has support for recursion, but it's generally slow and should be used in circumstances were the recursion limit is minimal. The following example recurses through a directory and collapses all empty directories. Its use is novel at best and most likely not usable in the current condition.
#!/bin/env bash
# Recursively descend into DIR and remove any superfluous
#+directories. A superfluous directory is a directory
#+that contains no regular files or is an empty leaf node.
function collapse_dirs()
{
# Set the top level directory.
TOPLEVEL=${TOPLEVEL:=$1}
local DIR=$1
# Get a list of directories.
local DIRS=`find $DIR -mindepth 1 -maxdepth 1 -type d` >/dev/null 2>&1
for dir in $DIRS
do
collapse_dirs $dir
done
# If TOPLEVEL we cannot do anything past this point.
if [ "$DIR" = "$TOPLEVEL" ]
then
unset TOPLEVEL
return
fi
# DIRS may have changed. Refresh
local DIRS=`find $DIR -mindepth 1 -maxdepth 1 -type d` >/dev/null 2>&1
local FILES=`find $DIR -mindepth 1 -maxdepth 1 -type f` >/dev/null 2>&1
# If this DIR has no FILES or DIRS, it's an empty leaf node. Delete.
if [ "${#FILES}" -eq "0" ] && [ "${#DIRS}" -eq "0" ]
then
echo "$DIR is an empty leaf node: deleting"
rmdir $DIR >/dev/null 2>&1
# If DIR is one below TOPDIR, at this point cannot do anything.
elif [ "${DIR%/*}" = "$TOPDIR" ]
then
return
# Now DIR has no FILES but child DIRS. Promote them and delete.
elif [ "${#FILES}" -eq "0" ]
then
echo "$DIR is an empty directory: collapsing"
mv -t ${DIR%/*} $DIRS >/dev/null 2>&1
rmdir $DIR >/dev/null 2>&1
fi
}
function dir_stats()
{
local ALL_FILES=`find $1 -type f`
local ALL_DIRS=`find $1 -type d`
local NUM_FILES=0 ; local NUM_DIRS=0
for file in $ALL_FILES; do ((NUM_FILES++)); done
for dir in $ALL_DIRS ; do ((NUM_DIRS++)); done
echo "Found $NUM_FILES files in $NUM_DIRS directories."
}
COLLAPSE=${1?"No dir specified"}
dir_stats $COLLAPSE
collapse_dirs $COLLAPSE
rm -fr $COLLAPSE_DIR
dir_stats $COLLAPSE
exit 0