Find and remove all empty directories using the Linux command line
In order to find and remove all empty subdirectories in the current directory (.
) recursively, use this command:
find . -depth -type d -print0 | xargs -0 rmdir
This command will **only remove empty directories!**Any file or non-empty directory won’t be modified.
Explanation of what the parts mean:
find
: Use the find command to find directories recursively.
: Start recursing from the current directory. In case you want to start from a different directory, use that directory name here.-type d
: Only find directories - ignore files-depth
: Before printing a directory name, print all its sub-directory names. This avoids having to run this command repeatedly because the parent directory can’t be removed since its empty sub-directories need to be removed first-print0
When printing all the directories that have been found, print a NUL character between directories. This is required in order to handle spaces in the directory names correctly| xargs
: Pipe the directories toxargs
, a program that runs-0
: Split the input by NUL characters instead of newlines. This corresponds with the-print0
option tofind
and is required to handle spaces in directory names correctly.rmdir
: For each directory found, runrmdir
i.e. try to remove the directory if it’s empty.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow