IT management/strategy

Unix tip: Recursively removing empty directories

April 29, 2009, 01:53 PM — 

As you undoubtedly know, the rmdir command will remove an empty directory but, if a directory contains files, it will balk and report "Directory not empty". To remove directories which are in fact empty is then easy. In any file system containing multiple directories, you can issue the "rmdir *" command knowing that only the empty directories will be removed.

To recursively remove empty directories, you could try a mix of the find and rmdir commands. For example, this command would remove numerous directories yet leave all the populated ones:

find . -type d -print | xargs rmdir

If you don't want to see all the "Directory not empty" errors, you can send standard error to /dev/null:

find . -type d -print | xargs rmdir 2>/dev/null

Looking for directories with find and then removing them has one drawback, however, If a directory becomes empty in the process of removing a directory that's inside of it, the parent directory will not be removed because find will detect it before it finds its child directory and it won't yet be empty.

You could run one of the commands shown above multiple times, maybe until no more "Directory not empty" errors appear. Alternatively, you could run a script like this one that uses find to create a list of directories, reverses the list so that child directories appear before their parents and then runs a rmdir against each directory in the list. In this way, all of the empty directories are removed in one pass.

#!/bin/bash

# get directory list
find . -type d -print > dirs$$

# reverse the listing
tail -r dirs$$ > revdirs$$

while read dirname
do
    rmdir $dirname 2>/dev/null
done < revdirs$$

# clean up
rm dirs$$
rm revdirs$$

One of the core commands in this script is the tail -r command. This command reverses the contents of a file or of any input piped to it. In fact, this command is so useful for this operation that you could reduce the script above to this one-liner:

find . -type d | tail -r | xargs rmdir

Or, again, if you don't want to see all the "Directory not empty" complaints, pipe the error output of this string of commands to /dev/null:

find . -type d | tail -r | xargs rmdir 2>/dev/null

As a one-liner, this command lends itself to use as an alias.

$ alias rmEmptyDirs="find . -type d | tail -r | xargs rmdir 2>/dev/null"

If you want to test this alias, create a directory under /tmp and populate it with a series of new directories.

Sign up for ITworld's Daily newsletter
Follow ITworld on Twitter @IT_world

I like it!
Comments

Or just use the "-depth" option on find

The -depth option makes "find" search sub-directories first. This should do it:

find . -type d -depth -print | xargs rmdir
| reply

With GNU find, it's even easier

In addition to the -depth switch, systems using Gnu find have an -empty switch that matches on empty files or directories. Your command can be shortened to:

find . -depth -type d -empty | xargs ...

I've looked in some older versions of the Gnu findutils package and it's been there some time now.
| reply
peer-to-peer

Esther Schindler
If the comments are ugly, the code is ugly

claird
SVG a graphics format for 21st century

pasmith
Take Chrome OS for a test spin

Sandra Henry-Stocker
Solaris Tip: Have Your Files Changed Since Installation?

sjvn
64-bits of protection?

jfruh
Android fragments vs. the iPhone monolith

mikelgan
What Gizmodo missed about the Pro WX Wireless USB disk drive

 

Sidekick: The Good News & the Bad News
Either way you look at it Microsoft Data Center management did not follow standards or best practices in this failure. In which case it makes me wonder more about the outsourcing of corporate data much less personal data.
- mburton325

Join the conversation here

The Daily Tip

The Daily TipQuick, practical advice for IT pros. Made fresh daily.

Hot tips:

Want to cash in on your IT savvy? Send your tip to tips@itworld.com. If we post it, we'll send you a $25 Amazon e-gift card.

Newsletters

Subscribe to ITWORLD TODAY and receive the latest IT news and analysis.

I would like to receive offers via email from ITworld partners.
By clicking submit you agree to the terms and conditions outlined in ITworld's privacy policy.
Featured Sponsor

AISO founders envisioned a Web hosting company that was environmentally friendly. While the company employed energy-efficient innovations like solar panels, its infrastructure produced unacceptable power and cooling requirements. Find out how AISO leveraged AMD technology to overcome their challenge in this case study white paper.

In this whitepaper, Scalar explores the opportunity to change the landscape with respect to mission critical databases built around Oracle. Leveraging technologies such as Linux, high-end commodity processing power and Oracle RAC technology to architect, design, build and maintain database infrastructure that delivers maximum availability, reliability and performance at a fraction of traditional cost.

On a typical day, weather.com, the Web site for The Weather Channel in Atlanta, serves up between 15 million and 20 million page views. But in September 2004, when back-to-back hurricanes ransacked Florida, the peak traffic on one day more than tripled: over 70 million page views by more than 7 million unique visitors. Read the full success story now.

Marketplace