10

Is there a command to execute in Bash that deletes all empty folders recursively until there is no empty folder in the tree? I could execute this:

find . -type d -empty | xargs -I '{}' rmdir {}

repeatedly until there is no more empty folders, but I am looking for something a bit more efficient. Especially since that to know whether there are empty folders left, I would have to execute the same command, i.e. two calls to find . -type d -empty in each iteration.

0

1 Answer 1

27

This is simple, given the GNU find utility:

find . -type d -empty -delete

This will delete empty directories; since the -delete option implies the -depth option, it will delete directories that only had empty directories underneath them, so there's no need to run it multiple times.

1
  • This was not working properly for me where I was specifying multiple paths and I discovered that I needed to place my ORed -path instructions before -delete into a group like this: find / -type d -empty \( -path /pathA -or -path /pathB \) -delete
    – Compholio
    Commented Nov 20, 2023 at 21:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.