How can I recursively delete all empty files and directories in Linux?

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.


Here's a two command solution

Delete empty files

find Parent/ -type f -size 0 -delete

Try to remove all directories

find Parent/ -type d -depth -print0 | xargs -0 rmdir 2>/dev/null

NB rmdir can't remove non-empty directories, thus it's safe to run but will produce errors, which we are hiding

As above, but being a little more specific about the error messages being ignored. Might need to amend if the message varies across distros.

find Parent/ -type d -depth -print0 | xargs -0 rmdir 2>&1 \
  | grep -iv "Directory not empty$"

You can also do this with the fd tool:

fd -t e -x rm -r

https://github.com/sharkdp/fd

Tags:

Linux

Shell

Bash