Jul. 19th, 2024
2024年 6月 14日

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:


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:


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
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF