Linux Shell Script To Delete Empty Directories

Linux shell script that search for empty directories and delete them. If system administrator don'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. Script will confirm before it deletes the empty directory.

linux shell script

Linux Shell Script

#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

[email protected]:~$ /tmp/test
Remove empty directory /tmp/test/test1: [No/yes] yes
Remove empty directory /tmp/test/test3/test5: [No/yes] yes
[email protected]:~$

About Bobbin Zachariah

Founder of LinOxide, passionate lover of Linux and technology writer. Started his career in Linux / Opensource from 2000. Love traveling, blogging and listening music. Reach Bobbin Zachariah about me page and google plus page.

Author Archive Page