GTKC Knowledgebase
A little bit of wisdom
How do I remove empty directories in Linux?
Posted by  Admin on


Update: 06/2023 This post is rather dated now.

Simply use the find command instead.

find /path/to/dir -empty -type d -delete


And for empty files:
find /path/to/dir -empty -type f -delete


Old original post.

You can use program called cleanlinks. The cleanlinks program searches the directory tree descended from the current directory for symbolic links whose targets do not exist, and removes them. It then removes all empty directories in that directory tree. It was originally created for symbolic links based directories but works with normal directories too.

For example if you want to remove all empty directories from /tmp directory, type the command:
$ cd /tmp
$ cleanlinks

Please note that cleanlinks command is part of XFree86 project. Another method is to use combination of shell commands in a script:

Create a file called rm_emptydirs.sh and add the following:
#/bin/bash
DIR="$1"
 [ -d $DIR ] && [ $(ls -l $DIR | wc -l) -eq 1  ] && rmdir $DIR ||  :

Save and make the script executable:
chmod +x rm_emptydirs.sh

Then run it:
$ rm_emptydirs.sh dir1


Tags: Filesystem , Linux

Return to home page: Home