Welcome to MSDN Blogs Sign in | Join | Help

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.

Published Thursday, April 17, 2008 7:00 AM by oldnewthing
Filed under:

Comments

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:15 AM by SRS

I like the advice that goes with Empty Folder Nuker v1.2.0 as well: "Now of course you should be careful not to delete important files - that much should be a given". Wise words indeed.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:28 AM by Danielw

Just don't run that if you're a purist like me and have no desktop icons.  Windows kinda goes nuts.  At least it did the last time I tried to run it.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:34 AM by Karellen

I can't figure out from the linked page whether or not the program also deletes empty files first. The guy seems completely confused about the distinction between files and folders, making it unclear what the program does.

It's entirely possible to conclude from what he's written that he considers a folder that contains files, all of which are 0 bytes in length, as being empty. In which case the program might delete all empty files (0 bytes in length) first and then delete any folders that are empty, including folders that have just been emptied by removing 0-byte files.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:48 AM by Rajesh

This script fails if the directory name containes any space(blank) charecters.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:54 AM by John

I would rather gauge my eyes out, thank you very much.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:55 AM by ak

I made a program that does this awell, I'm sure you could do it in a batch file, but it needs more handling than you have here.

On win9x, there are a couple of folders that can be empty, but you don't want to delete them because it messes up the shell (IIRC the desktop and all users desktop folders)

Also, you don't want to delete empty guid folders (Don't know the proper name for those) ex: "Control Panel.{control_panel_guid}"

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 11:52 AM by John Vert

To fix the problem with spaces in paths, use the delims option:

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

Then it will not tokenize the line.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 11:59 AM by Tom

Actually, I really do enjoy working with batch files.  Some of my earliest programming was writing .bat files for DOS (who can forget autoexec.bat?).  Things have gotten much more sophisticated as Windows has added features to the language, and yet it retains its simple and familiar feel.  It has a certain charm and accessibility which I find completely absent in other shells and scripting environments.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:02 PM by Franci Penov

Or you could just do rd /s /q /f "<empty folder>". Saves you additional 60 chars. :-)

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:20 PM by KJK::Hyperion

or, losing the heinous "usebackq" option:

for /f "tokens=*" %%d in ('dir /ad/b/s ^| sort /R') do rd "%%d"

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:22 PM by KJK::Hyperion

Franci: don't even JOKE. rd /s deletes all subfolders AND files

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:31 PM by anonymous

Why the unnecessary usebackq? To use the quotes, because yor don't know how to escape the pipe symbol? Or what? It can be so simple:

for /f "delims=" %%i in ('dir /s /b /ad ^| sort /r') do rd "%%i">NUL

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:37 PM by Fenster

When I want to delete all folders (not necessarily empty ones).  I use robocopy using /MIR option and set the source folder as an empty folder and the destination as the folders I want to delete e.g:

SET SOURCE=N:\TempDir

SET DEST=N:\Trash

MD %SOURCE%

ROBOCOPY %SOURCE% %DEST% /MIR /R:01 /W:01

del %SOURCE%

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:37 PM by Mega Bloat

cmd.exe is 382 kb (winxp). What kind of bloatware is this?

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 12:48 PM by anon

Can somebody please provide a dummy's explanation of what usebackq is used for and how it's better than tokens?

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 1:07 PM by tkeane

@anon-

I've heard there are magical web-sites where you can type in words such as 'usebackq' and 'tokens' and get links to relevant articles about them...

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 1:11 PM by Josh

@anon:

It's got nothing to do with tokenizing.  usebackq simply makes the command in the parentheses be delimited with backquotes, ` (it's right above the Tab on most QWERTYs), instead of normal quotes, ',  which allows for you to use a number of symbols in the command string directly which would otherwise have to be escaped.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 1:36 PM by anon

@Josh:

Thanks.  Exactly what I was looking for.

@tkeane:

That type of comment doesn't help anyone.  The first page of results from http://www.google.com/search?q=usebackq:

Has 3 explanations that are identical, 3 that require you to login to a site and the rest are useless.

Thanks to Josh there will now be one more explanation on the first page when people go to these magical web sites.

Is it really so bad to ask for an alternate explanation?

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 4:17 PM by Cooney

this is all too complicated. Install some unix tools and do this:

find <dir> -depth -type d -empty|xargs rmdir

as a bonus, if I screwed up the command, rmdir fails when the dir isn't empty.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 4:35 PM by oskopia

I work with batch files - not often, but if I need something, they can do. But I have heard, Basic ... some sort of Basic is much better for it. Unfortunately I am not used to it, but to batch files.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 5:59 PM by njkayaker

@anon: "That type of comment doesn't help anyone."

Your original post is indistiguishable from what some one too lazy to to a web search would have posted. (Hint: provide some evidence that you've performed the search before asking the question.)

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 6:18 PM by anonymous

@Josh: Adding the usebackq and trying to find the horribly stupid backquotes on an EN-US keyboard (hint: not there, you have to use AltGr+XXXX) is definitely much less efficient than simply escaping one or too ampersands or pipes.

@anon: tokens=* instead of delims= is just less understandable and non-obvious.

And for the usebackq: Where's your problem with typing "for /?" on your command prompt?

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 6:26 PM by Neil

Using the -empty primary for find doesn't work, because as Raymond says, "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." Therefore you have to find all subdirectories and rely on rmdir only removing the empty ones.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 6:48 PM by Mike Heath

It's blog posts like this that make me glad I have Cygwin.  It's a simple rm -rf dirname.

[Um, that removes nonempty directories too. -Raymond]

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 6:50 PM by Cooney

> Using the -empty primary for find doesn't work, because as Raymond says, "we enumerate the directories bottom-up rather than top-down.

that's what -depth is for - it enumerates bottom up.

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 8:19 PM by chrismcb

@cooney

How is "find <dir> -depth -type d -empty|xargs rmdir" any less complicated?

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 9:01 PM by steveg

# re: One-line batch script to delete empty directories

Thursday, April 17, 2008 10:56 PM by Jeff Tyrrill

Once again, we encounter the main reason that the command line is ill-equipped for any serious task: This script does not work with non-ASCII (such as Japanese) characters. Tested on Vista.

I note that the linked program does support Unicode (even though it had to be "added" after the first release).

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 12:37 AM by MadQ

Jeff: Out of curiousity, have you tried changing the console's code page? For example, to set the code page to UTF-8: MODE CON CP /SELECT=65001

Or maybe 932 (ANSI/OEM Japanese; Japanese (Shift-JIS)) or one of the other japanese code pages would work. I'm just stabbing in the dark; I know nothing about Japanese.

# Cancellare le cartelle orfane con una sola riga di comando | Il blog che non c'??

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 8:12 AM by BryanK

Eeew, piping to xargs!

On Unix, any byte is valid in a file or directory name except the zero byte and the byte used for the ASCII forward slash character (0x2f).  Piping to xargs fails if any directory anywhere in the output of find has a newline in its name.

What does work is:

find -depth -type d -empty -exec rmdir {} \;

to have find execute rmdir directly.

(Of course all this requires some sort of Unix find to be installed, which means it's a bad solution for Windows.  It also breaks as soon as you need to run it on some machine that you don't own...)

# Enjoying batch files

Friday, April 18, 2008 8:28 AM by Gerald

Actually, these postings are the ones I love the most.

I doubt I'll ever have to program scrollbar behaviors, but this kind of stuff is extremely useful. It doesn't just show a specific solution to a specific problem, but also introduces a line of thinking which makes me consider "oh, I could actually use this for something else..."

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 11:30 AM by anonymous

Jeff and MadQ, did you ever consider "cmd /u"?

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 12:35 PM by Yuliy

@chrismcb

It's different because it fails to delete a directory which has only an empty directory as a subdirectory. Raymond's solution tries to rd every directory. It succeeds for empty directories (when it gets to them) but fails for those that are empty.

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 12:46 PM by Adam

@Cooney and BryanK

Even simpler Unix one-liners that don't require piping or spawning new processes:

To delete 0-byte files and empty directories:

find <dir> -empty -delete

To delete empty directories but not 0-byte files:

find <dir> -empty -type d -delete

Note that the -delete option implies -depth.

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 1:08 PM by Anonymous Coward

"Where's your problem with typing "for /?" on your command prompt?"

Some of us don't use Windows but still enjoy Raymond's informative and insightful posts.

Typing "for /?" on a Bourne shell won't do any good.

(Of course, one could try running Wine's cmd.exe and typing "for /?" there... Assuming they implemented the help parts of cmd.exe, that they implemented the "advanced" functions of cmd.exe, that they didn't make any mistake on the help text, and that you are running on a i386-derived platform.)

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 1:12 PM by BryanK

-delete?  Wow, I had no idea that existed...  Thanks!  :-)

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 2:43 PM by Jay Bazuzi

I was a CMD scripting nut for many years, but thanks to PowerShell, I can cut off the oxygen supply to that part of my brain.

One thing that most of the alternative solutions proposed here seem to miss is that if a directory contains no files in any of its subdirectories, Raymond's one-liner will delete them.  My proposal fails that test, too, I'm afraid, but I offer it here anyway as an example of the wonder of PowerShell.

Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item

or, more tersely,

gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri

# re: One-line batch script to delete empty directories

Friday, April 18, 2008 6:48 PM by Neil

>One thing that most of the alternative solutions proposed here seem to miss is that if a directory contains no files in any of its subdirectories, Raymond's one-liner will delete them.

And they continued to do so after I quoted Raymond, which just goes to show that nobody actually reads anything he writes. (Now, where was that article on write-only memory?)

# re: One-line batch script to delete empty directories

Saturday, April 19, 2008 1:08 AM by GreaseMonkey

> cmd.exe is 382 kb (winxp). What kind of bloatware is this?

It does more than just delete files.

By the way, /bin/bash is 661KB. If you're typing that on a mac, I could probably guarantee it's more bloated than cmd.exe. /bin/busybox is 440KB or something, and it's got a lot of stuff; I'm unsure if it matches cmd.exe though.

In honour of Linux bloatware though... /bin/true and /bin/false are 11KB here; I can make a file in DEBUG.EXE to do the same thing, and that takes up only 5 bytes. With an MZ header (DOS EXE), I could probably do that in 37 bytes. Although, someone made a Linux ELF program in a very similar vein which was only 46 bytes, even though it walked all over the header. The smallest PE file (Windows EXE) is about 81 bytes or something, and it doesn't work on 2000/XP due to the lack of headers.

As for the deletion script, I haven't worked out how to do the same in a bourne shell, but it'd be a lot better than 260KB. Heck, I could do a C program better than that, maybe even a C++ one or a Java one using GCJ.

So yeah, goes both ways.

# .neteffect, April 20, 2008 | BlogWell

Sunday, April 20, 2008 4:09 PM by .neteffect, April 20, 2008 | BlogWell

# re: One-line batch script to delete empty directories

Sunday, April 20, 2008 11:52 PM by Jonathan Camacho

@BryanK

The -print0 / --null option can be used to let xargs function when the input filenames contain whitespace.

find -depth -type d -empty -print0 | xargs --null rmdir

# re: One-line batch script to delete empty directories

Monday, April 21, 2008 2:49 PM by Ben Voigt

@Camacho

That still collects all the names first, which:

(1) Doesn't delete directories that are recursively empty.

(2) Risks exceeding the maximum command-line length.

Better options have already been given.

# re: One-line batch script to delete empty directories

Monday, April 21, 2008 3:53 PM by David Walker

@Clooney: Now you have two problems.  (It seems like I have heard that somewhere before...)

# re: One-line batch script to delete empty directories

Tuesday, April 22, 2008 12:38 PM by Rick

Jesus Christ Ray every time you post its like planting a seed, branches grow off in all kinds of crazy directions.

Thanks for posting the oneliner, I've been trying to figure that one out for some time. I had not thought of relying on rd's inability to remove non-empty folders.

# conormulligan.com / blog &raquo; One-line batch file to delete empty directories

# links for 2008-05-06 &laquo; LAN b4 Time

Monday, May 05, 2008 8:33 PM by links for 2008-05-06 &laquo; LAN b4 Time
New Comments to this post are disabled
 
Page view tracker