How do I delete all empty directories in a directory from the command line?

Say I have a directory named foo/. This folder includes subdirectories. How can I delete all the empty directories in one command?


Solution 1:

Try this command:

find . -empty -type d -delete

The find command is used to search for files/directories matching a particular search criteria from the specified path, in this case the current directory (hence the .).

The -empty option holds true for any file and directory that is empty.

The -type d option holds true for the file type specified; in this case d stands for the file type directory.

The -delete option is the action to perform, and holds true for all files found in the search.

Solution 2:

You can take advantage of the rmdir command's refusal to delete non-empty directories, and the find -depth option to traverse the directory tree bottom-up:

find . -depth -exec rmdir {} \;  

(and ignore the errors), or append 2>/dev/null to really ignore them.

The -depth option to find starts finding at the bottom of the directory tree.

rm -rf will delete all the files in the directory (and its subdirectories, and ....) AND all the directories and everything.