We can use find command to delete all empty files and directories recursively
To delete empty files
$ find ./path -type f -empty -delete
To delete only empty directories
$ find /path -type d -empty -delete
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
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
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.
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
$ find a -maxdepth 3 a a/filea.txt a/b a/b/c a/b/c/filec.txt a/b/fileb.txt
Let’s say if you want to delete only the deepest or very last directory and files which are empty. You can do so,
find a -maxdepth 3 -mindepth 2 a/b/c a/b/c/filec.txt a/b/fileb.txt
You can delete them by adding -delete action to above command
find a -maxdepth 3 -mindepth 2 -empty -delete
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.