Remove empty directory trees (removing as many directories as possible but no files)

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

find ROOTDIR -type d -empty -delete

same as

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

but uses the built in “-delete” action.

Note that “-delete” implies “-depth”.

Method 2

Alexis is close. What you need to do is this:

find . -type d -depth -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). 🙂

Method 3

I would try this:

find ROOTDIR -type d -depth -exec rmdir {} ;

Method 4

Here are some requirements before we can do it safely:

  1. remove subdirectories first and then upper level directories, i.e. we need to sort directory listing or use rmdir –parents flag
  2. start ROOTDIR always with / or ./ to avoid surprises with files beginning with –
  3. use NUL terminated list of directories to work with directory names with spaces

Here is how I’d do that in shell:

find ./ROOTDIR -type d | sort -r | tr 'n' '00' | xargs -0 rmdir --ignore-fail-on-non-empty

If you don’t mind some redundant errors then you can just force removing all directories with parents and you don’t need to do any sorting (you can’t sort NUL terminated strings which adds need to tr)

find ./ROOTDIR -type d -print0 | xargs -0 rmdir --ignore-fail-on-non-empty --parents

Method 5

rmdir $(find ROOTDIR -type d | sort -r)

Method 6

I would do this:

find ROOTDIR -type d | xargs -0 -I {} rmdir {}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x