Skip to main content

Linux - Delete empty directories recursivly

find . -type d -empty -delete

Important: The position of the flags matters! - Having -delete before the check, it deletes everything AND then does the check. As mentioned by @"lefractal"#3 you can replace the -delete flag with a trash-cli command to recover any deleted information find . -type d -empty -exec trash-put {} \;. Additional information can be found in this article.

Simple PoC:

user@pleasejustwork:~/9_temp/delete$ mkdir -p ./this-is-a-test/{this-is-empty,this-is-not-empty/this-is-empty-again} && touch ./this-is-a-test/this-is-not-empty/not-empty.txt

kuser@pleasejustwork:~/9_temp/delete$ tree
.
└── this-is-a-test
    ├── this-is-empty
    └── this-is-not-empty
        ├── not-empty.txt
        └── this-is-empty-again

4 directories, 1 file
kuser@pleasejustwork:~/9_temp/delete$ find . -type d -empty -delete
kuser@pleasejustwork:~/9_temp/delete$ tree
.
└── this-is-a-test
    └── this-is-not-empty
        └── not-empty.txt

2 directories, 1 file

E-Mail hellofoo@ittafoovern.comcom