One-line batch script to delete empty directories

Raymond Chen

Raymond


You don’t need a whole 260KB program to do it
.
This batch file does the trick just fine:

for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

I call it rdempty.cmd.

This is the long-forgotten follow-up to

Performing an operation in each subdirectory of a directory tree
from batch
.
We’re using the same technique as in that article,
but pumping the result through “| sort /R
to reverse the order of the enumeration so we enumerate
the directories bottom-up rather than top-down.
This is important for deleting empty directories
because you have to remove the subdirectories before
you remove the parent.

Disclaimer:
I doubt anybody actually enjoys working with batch files,
but that doesn’t mean that tips on using it more effectively
aren’t valid.
If you would rather gouge your eyes out than use the confusing
command prompt batch language,
then you are more than welcome to use
the scripting language of your choice instead.
At no point in this article am I saying that this is the only way
or the best way to do it.
But it’s definitely smaller than a 260KB program.

Raymond Chen
Raymond Chen

Follow Raymond