how can I recursively delete empty directories in my home directory?

Possible Duplicate:
How to remove all empty directories in a subtree?

I create directories very often, scattered over my home directory, and I find it very hard to locate and delete them.

I want any alias/function/script to find/locate and delete all empty directories in my home directory.

Asked By: Santosh Kumar

||

You can call rmdir on every directory, since rmdir will only delete a directory if it is empty:

find "$HOME" -type d -exec rmdir {} + 2>/dev/null

If you also want to print the directories being removed, you will need to check if they are empty:

find "$HOME" -type d -exec bash -c 'shopt -s nullglob; shopt -s dotglob; files=("$1"/*); [[ ${files[@]} ]] || rmdir -v "$1"' -- {} ; 

Here is a pure bash example (version 4 or higher):

shopt -s globstar
for dir in **/; do
   files=("$dir"/*)
   [[ ${files[@]} ]] || rmdir -v "$dir"
done
Answered By: jordanm

The find command is the primary tool for recursive file system operations.
Use the -type d expression to tell find you’re interested in finding directories only (and not plain files). The GNU version of find supports the -empty test, so

$ find . -type d -empty -print

will print all empty directories below your current directory.

Use find ~ -… or find "$HOME" -… to base the search on your home directory (if it isn’t your current directory).

After you’ve verified that this is selecting the correct directories, use -delete to delete all matches:

$ find . -type d -empty -delete
Answered By: Baldrick
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.