A note on using
two percent signs inside batch files, when using the
for command. There are other similar cases as well:
The command line interpretor reads the batch file line by line. When it comes across a line that reads for example:
set PATH=%PATH%;C:\TOOLS
then it will append the directory C:\TOOLS to the current path. This is achieved by doing a replacement before execution. When the line is read, the CLI will replace the expression %PATH% with the string that is stored inside the environment variable called PATH (usually a list of folders, separated by semicolons). Lets assume for the sake of easy examples that the PATH would be C:\WINDOWS;C:\WINDOWS\COMMAND at the beginning. Replacement leads to the following command being executed:
set PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\TOOLS
Relacement (also called expansion of variables) is done first, execution is done second.
Now the
for command is special, as you don't want the variable %f to be expanded, you want to assign something to it. If you were to write on the command line (DOS prompt) this:
for %x in (1 2 3) do echo %x
you would get what you want, because it is not inside a batch file and is correct syntax.The same line inside a batch file would produce a syntax error, secondary to expansion of %x to an empty string, resulting in the execution of:
for in (1 2 3) do echo
and that is missing the necessary name for the variable.
The solution is the special expansion of double percent signs: "%%" expands to (the shorter) "%", and the line:
for %%x in (1 2 3) do echo %%x
will expand to the correct line:
for %x in (1 2 3) do echo %x
Note that the name of the variable (here: x) is just added on after the expansion ot "%%", just like all the other letters.
Short: at the prompt use one, in batch files use two percent signs. (Applies
only to special commands like
for)
Greetings
Wolf