Home » Shell Scripts » Shell Script to Delete Empty Directories in Linux

Shell Script to Delete Empty Directories in Linux

This tutorial shows how to search for empty directories and delete recursively using a shell script. If the system administrator doesn't want to keep empty directories, this script can quickly remove all of them.

You can input the path where you need to search for empty directories. The script will confirm before it deletes the empty directory.

Bash Script Delete empty Directories

#Check if user input parameter, if not ask to enter directory
if [ x"$1" = "x" ]; then
#Ask user to input directory where to start search for empty directories.
echo -n "Please enter directory where to delete empty folders: "

#we read input
while read dir


#we check if input empty
test -z "$dir" && {

#if input empty – we ask once more to input directory
echo -n "Please enter directory: "



#if entered no empty data – continue to do other things


#if user entered parameter do next:
#dirname will be passed parameter
#this check if directory exist, exit if not
if [ ! -d $dir ]; then
echo "No such directory"
exit 1

#We will store list of all directories in temporary file

# we search for all directories
find $dir -type d > $DirList

#writing all directories to vatiable
dirs=`cat $DirList`

#start checking every directory
for dir in $dirs


#we are checking if directory is empty
[ `ls $dir | wc -l` -lt 1 ] || continue
#this ask user if really delete directory
echo -n "Remove empty directory $dir: [No/yes] "
#reading users answer:
read answer
#Checing answer, if yes – we will delete folder, nothing in other case:
if [ "$answer" = "yes" ]; then
rmdir "$dir"

Shell Script Output

Let's check console output our shell script

test@centos:~$ rmempty.sh /tmp/test
Remove empty directory /tmp/test/test1: [No/yes] yes
Remove empty directory /tmp/test/test3/test5: [No/yes] yes