Linux Bash – Recursively Delete All Empty Files and Directories

bashlinuxshell

How can I recursively cleanup all empty files and directories in a parent directory?

Let’s say I have this directory structure:

Parent/
  |____Child1/
        |______ file11.txt (empty)
        |______ Dir1/ (empty)

  |____Child2/
        |_______ file21.txt
        |_______ file22.txt (empty)

  |____ file1.txt

I should end up with this:

Parent/
  |____Child2/
        |_______ file21.txt

  |____ file1.txt

Best Answer

This is a really simple one liner:

find Parent -empty -delete

It's fairly self explanatory. Although when I checked I was surprised that it successfully deletes Parent/Child1. Usually you would expect it to process the parent before the child unless you specify -depth.

This works because -delete implies -depth. See the GNU find manual:

-delete Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete fails, find's exit status will be nonzero (when it eventually exits). Use of -delete automatically turns on the -depth option.


Note these features are not part of the Posix Standard, but most likely will be there under many Linux Distribution. You may have a specific problem with smaller ones such as Alpine Linux as they are based on Busybox which doesn't support -empty.

Other systems that do include non-standard -empty and -delete include BSD and OSX but apparently not AIX.

Related Question