Unix tip: Recursively removing empty directories

By Sandra Henry-Stocker  5 comments

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. The easiest way to do this is to use the mkdir -p command:

cd /tmp/testing
mkdir -p a/b/c/d/e/f/g/h/i/j
mkdir -p d/r/a/g/o/n/f/l/y
mkdir -p d/i/t/c/h
mkdir x
mkdir y
mkdir z

Then touch a file somewhere in the newly created directory structure:

touch a/b/c/myfile

If you then run the rmEmptyDirs alias, you will find that only the a, a/b and a/b/c directories and the file "myfile" remain.

The mkdir -p command, which creates a directory structure by creating all the directories along the requested path that don't already exist, has a partner in rmdir -p that removes all the directories along the way, provided they are empty. This leads to a further simplification of our alias. Now we can reduce it to this:

alias rmEmptyDirs="find . -type d | xargs rmdir -p"

or:

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

Using rmdir -p, the list reversing operation is no longer needed. If you don't suppress standard error, you will note that this command will refuse to remove directories that it finds until it reaches one that is empty. At that point, it will remove all of its empty parents and grandparents.

Another simplication is to use the rmdir command's -s option to suppress the error output instead of piping it to /dev/null. Now, we have the ultimately simply command for removing empty directories:

alias rmEmptyDirs="find . -type d | xargs rmdir -ps"

You can't make the process much easier than that! Our original rmdir command with a couple command options only has to be run once and gets rid of all empty directories in its path.

5 comments

    TheGingerDog 26 weeks ago
    Pah, sorry all... stupid comments didn't appear until after I'd created an account and logged in etc etc.

    Find also has a -delete flag which can save the xargs rmdir stuff too.
    TheGingerDog 26 weeks ago
    Or you can use the -depth option to find, which should make it depth first... and remove the requirement to mess around with tail etc etc.
    Anonymous 45 weeks ago
    The -depth option makes "find" search sub-directories first. This should do it:find . -type d -depth -print
    Anonymous 45 weeks ago
    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
    Anonymous 45 weeks ago in reply to Anonymous
    find . -depth -type d -empty

      Add a comment

      Post a comment using one of these accounts
      Or join now
      At least 6 characters

      Note: Comment will appear soon after you have activated your account.
      Obscene/spam comments will be removed and accounts suspended.
      The information you submit is subject to our Privacy Policy and Terms of Service.

      ITworld LIVE

      IT Management/StrategyWhite Papers & Webcasts

      White Paper

      Evaluator Group: Storage Federation - IT Without Limits (Analysis of HP Peer Motion with Storage Federation)

      As the role of IT increases within organizations, the need to move data when and where it is needed is critical to support emerging business requirements. This has become increasingly difficult due to the huge growth of data volumes. This white paper sponsored by HP + Intel evaluates a solution that aims to enable the movement of data without physical limitations. Read now and see how this could enable agility and efficiency.

      White Paper

      ESG Lab Validation Report: HP Data Protector & Deduplication Solutions

      Many organizations have deployed disk-to-disk backup technologies to improve the speed and reliability of their backup and disaster recovery operations. A growing number of these now look to data deduplication to enhance retention periods and reduce costs. This ESG Lab Validation Report sponsored by HP + Intel examines a number of backup and recovery solutions and evaluates their ease of implementation as well as their ability to improve reliability and reduce costs.

      White Paper

      Business Value of Blade

      The nature of the blade platform makes system management, monitoring and provisioning easy and efficient. Access this resource to learn how blade migration will save your data center time and money while increasing performance.

      White Paper

      Accelerate time to application value

      For your IT organization to keep pace with the business, you need a new, faster approach to infrastructure deployment-an approach that increases agility and accelerates time to application value. That's HP Converged Systems. Built on Converged Infrastructure, these systems deliver the industry's first portfolio of pre-integrated, tested, and optimized infrastructure solutions for applications running in virtual, cloud, dedicated, or hybrid environments.

      White Paper

      Converged Infrastructure for Dummies

      As you know, everything is mobile, connected, interactive, and immediate. This is exactly why organizations need a highly agile IT infrastructure in order to keep pace with extreme fluctuations in business demand. This book will help you understand why infrastructure convergence has been widely accepted as the optimal approach for simplifying and accelerating your IT to deliver services at the speed of business while also shifting significantly more IT resources from operations to innovation.

      See more White Papers | Webcasts

      Ask a question

      Ask a Question