How do I remove empty directories in Linux?

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

admin has written 101 articles