Date
Oct. 18th, 2024
 
2024年 9月 16日

Post: Remove empty directory trees

Today is the A Memorial Day

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.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询