How-to: Double %% symbols, why are they needed in a batch file?

A common question asked by new batch file programmers is "why do we need to double the percent symbols when writing a FOR command?". On the command line %A works fine, so why does a batch need %%A?

To answer this we need to consider all the things in the batch language which use the % symbol:

Now you see the problem this presents, you can have two different types of variable with identical names and the CMD command shell parser needs a way to separate them.

How the CMD shell command line parser evaluates variables:

The CMD shell reads through each line of a batch file once from left to right, when it finds a percent sign it checks the next character and proceeds as follows:

When working at the command line (not in a batch script) there is no possibility of any batch file parameters %1, %2 etc so the logic above is not followed and hence FOR parameters on the command line only need a single %.

One other place where a percent character is used is as the modulus operator in the SET /A command, in a batch file this should always be passed as a pair of double %%'s.

Variable Names

It is worth also considering how this affects normal variables - this does not make for readable code, but just to prove a point, lets try to create a standard variable with a variable name that is numeric:

SET 1=Hello

You might expect that to create the variable %1%, but in a batch file it will Fail.

Even if the script was called without passing any parameter %1, the parameters take precedence, so %1% is evaluated as %1 plus an extra % at the end. Remember the command line is parsed left to right only once, so the %1 is evaluated before the second % is even read.
You can of course do SET 1=Hello at the command line and it will work!

Summary

So what have we learned from all this:

If you are aghast at the insanity of all these arcane rules, you should be learning PowerShell, it's awesome!

Related commands

The caret symbol ^ as the CMD Escape character, has to be doubled both within Batch files and at the command line.
The Batch Line Parser explained on Stack Overflow by Jan Erik (jeb) and Dave Benham, also more on % Expansion (same thread).
How-to: Parameters - Command Line Arguments %1 %~f1
How-to: Environment variables - Windows environment variables Env:


 
Copyright © 1999-2024 SS64.com
Some rights reserved