How to delete empty files and directories recursively

We can use  find command to delete all empty files and directories recursively

To delete empty files

To delete only empty directories

If you omit filter -type, it will delete both directories and files.

You can control the how deep the find  command can go and delete the empty directories and files.

Let’s say I have this directory tree

Directory Tree
Directory Tree

As you can see, we have 3 levels of directories (and files). All are empty, this is to give you better illustration.

To control how deep we search to delete empty files and directories and from which level we should delete. We would use the following two options

-maxdepth levels
Descend at most levels (a non-negative integer) levels of directories below the command line arguments. -maxdepth 0
means only apply the tests and actions to the command line arguments.

-mindepth levels
Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files
except the command line arguments.

These options (-maxdepth and -mindepth) should be provided immediately after the last path.

The simple find command below will print all files till level 3

Let’s say if you want to delete only the deepest or very last directory and files which are empty. You can do so,

You can delete them by adding -delete action to above command

Apparently only a/b/c/filec.txt and a/b/fileb.txt will be delete because the director c is not empty.

The command find is great utility that every linux geek should know.

Leave a Reply

Your email address will not be published. Required fields are marked *