Date
Sep. 12th, 2024
 
2024年 8月 10日

Post: Remove empty directory trees

Remove empty directory trees

Published 02:05 May 17, 2024.

Created by @ezra. Categorized in #UNIX/Linux, and tagged as #UNIX/Linux, #Ubuntu Linux.

Source format: Markdown

Table of Content

Suppose I have a dir tree like this:

ROOTDIR
    └--SUBDIR1
        └----SUBDIR2
            └----SUBDIR3

I am looking for a command such that when I input:

$ [unknown command] ROOTDIR

The whole dir tree can be deleted if there is no file but only dirs inside the whole tree. However, say if there is a file called hello.pdf under SUBDIR1:

ROOTDIR
    └--SUBDIR1
        └--hello.pdf
        └----SUBDIR2
            └----SUBDIR3

Then the command must only delete SUBDIR2 and below.

Well, what you need to do is this:

find . -depth -type d -empty -exec rmdir "{}" \;

That will first drill down the directory tree until it finds the first empty directory, then delete it. Thus making the parent directory empty which will then be deleted, etc. This will produce the desired effect (I do this probably 10 times a week, so I'm pretty sure it's right). :-)

# Run this to preview:
find . -depth -type d -empty -exec readlink -f "{}" \;
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系