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


Most recent Articles:
  • Notice Board 003: Progress is Progress
  • How to: Cisco ISE backup to SFTP repository with public key authentication
  • Dummy IP & MAC Addresses for Documentation & Sanitization
  • Deploying ISSO Commenting System for Static Content using Docker
  • Generate a Vanity v3 Hidden Service Onion Address with mkp224o