April 17th, 2008

One-line batch script to delete empty directories

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.

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.