Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using r.js as a build tool but as of today that tools doesn't give me the ability to delete empty folders in the build dir. I've found these two scripts

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

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

looking around the net but i always get

%%i was unexpected at this time.


%%d was unexpected at this time.

And i wouldn't know how to tell the script where my directory is.

My build script is

@echo off
where /q r.js || (
    echo requirejs node package is not installed. You must install node, npm and then run npm install -g requirejs
    goto :eof
node r.js -o

I need to tell the script to remove all empty directories which are located inside ../../js

share|improve this question
up vote 3 down vote accepted

For reason I never fully understood, for uses a different syntax inside and outside of batch files.

This command should work inside a batch file

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

In the command prompt (no batch file), you have to substitute %%i by %i:

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

Also, to suppress the The directory is not empty. error messages, use rd "%i" 2>NUL.

A simple rd "%i">NUL redirects the output (stdout), not the error messages (stderr).

share|improve this answer
This works perfectly. If i wanted to suppress all ( both output and error) messages how should i do? – Nicola Peluchetti Jul 3 '12 at 21:09
Just use both: rd "%i">NUL 2>NUL. In this case, >NUL is not needed, since rd doesn't produce any output. – Dennis Jul 3 '12 at 21:14

Note that the first script, i.e., the one below, DOES NOT work on directories with space characters.

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

The correct version should be here. Note that the use of the default spaces and tabs as delimiters MUST be disabled.

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

And please refer to Dennis's answer (the accepted one) for using the script on command prompt.

share|improve this answer
You don't need "usebackq" unless the command in (...) is using `, yours is using ". – DavidPostill Jul 18 '15 at 18:48
In addition usebackqdelims is invalid, there should be a space like usebackq delims – DavidPostill Jul 18 '15 at 18:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.