Solved Need help understanding batch commands/parameters

user0x12

New member
Local time
6:14 AM
Messages
15
Hello,

In this batch program (deletes temp files):

@echo off
cd %temp%
for /d %%D in (*) do rd /s /q "%%D"
del /f /q *

What does the "%%D" component signify and how is it used? Or rather, how does the "for" command work for that matter? I've looked at other explanations online and I can't seem to find a clear distinction between %%D and %D, for example.

I appreciate any input. Thanks.
 

My Computer

Computer type
PC/Desktop
OS
Windows 7 64-bit
In a batch for loop, this "%%D" signifies a dynamic variable that will expand to each item of a list of data that For produces. In this example, %%D expands to each directory found within the %temp% folder.

The for /d in (*) part of the command says to grab a list of all directories in the current working directory (which is %temp% in this case), and the command part of the loop: rd /s /q "%%D" is executed a finite number of times, where %%D expands to each item of data with each iteration of the loop.

The letter proceeding the percents is completely arbitrary. It does not have to be capital, or even a letter at all. The following are examples of valid dynamic variable names; %%A, %%h, %%6, %%0, %%#, %%_, %%$. Though, it's always best practice to use a capital letter; it's rare you'll come across anything else.

The writer of this batch script has appropriately chosen the letter D for its dynamic variable, as each iteration of the loop should expand %%D to a name of a directory.

"%D" does not exist within batch files. A single percent is used when you want to run the For command within a Command Prompt. So if you want to run for /d %%D in (*) do rd /s /q "%%D" in a Command Prompt, it would become for /d %D in (*) do rd /s /q "%D". It's just something you have to remember.


You may enter help for into a Command line to read more about the For loop. Or you can learn how to effectively use batch For Loops here.
 

My Computer

Computer type
PC/Desktop
OS
Windows 10, Windows 8.1 Pro, Windows 7 Professional, OS X El Capitan
Back
Top