How to Find and Delete Empty Directories in Linux

Many times empty directories get cluttered in the Linux file system, and it becomes a difficult task to manually search for and delete each of them. The command rmdir (remove directory) is used in Linux to delete empty folders.

The command is quite simple to use and the basic syntax is:

$ rmdir <empty folder name1> <empty folder name1> ... <empty folder nameN>

Here, ‘empty folder name1‘, ‘empty folder name2‘, etc. are the names of the folders including the full path. If the folders are in the same directory then, as you might already know, there is no need to write down full paths.

You can also use wildcard expressions to remove empty directories with patterns in their names. For example, to remove empty directories with the substring ‘test‘ in their name, run:

$ rmdir *test*
Remove Empty Directories
Remove Empty Directories

However, to use rmdir we always need to specify the name (or full path) of each empty directory to be removed. There is no option in rmdir to recursively look for empty directories and then remove them.

We make use of the functionalities of the find command in such cases.

Find and Remove Empty Directories in Linux

The find command is used to search for files and folders in Linux based on different parameters like filename, size, type, etc. We will use find to determine empty directories recursively and then execute rmdir to delete the found directories.

Use the argument '-empty' to look for empty objects and specify '-type d' to only find directories.

$ find path_of_folder_to_search -type d -empty

To find empty directories recursively in the same folder, run:

$ find . -type d -empty
Find Empty Directories
Find Empty Directories

Now, since we already have the recursively found list of empty directories, we use the '-exec' argument of the find command to run rmdir over them.

$ find . -type d -empty -exec rmdir {} \;

The placeholder {} substitutes each entry in the list of found directories and '\;' signifies the end of the command to be executed.

However, even with this, it will just do a single round of search and remove directories that are empty, but it will not remove directories that become empty after the first round of deletion.

To tackle this, we simply use the '-delete' option, which will repeatedly delete all empty directories till the top-level directory.

$ find . -type d -empty -exec -delete
Find and Delete Empty Directories
Find and Delete Empty Directories

This is how we can remove all empty directories recursively in Linux.


We learned how to use the rmdir command and find command in Linux to delete empty directories recursively. Learn more about these commands in their respective man pages:

$ man rmdir
$ man find

Thanks for reading and do share your thoughts below!

Got something to say? Join the discussion.