SoFunction
Updated on 2025-04-09

Detailed explanation of cmd batch escape character %

1. % is an ESCAPE character, which is usually translated into escape characters, but there are also more vivid translations of escape characters, escape characters, etc. That is to say, % not only escapes and replaces specific strings related to it with specific strings, but also is also "escaped". And similar to the escape character "\" in C language, double % will escape and escape to single %, and four % will escape to double %.

2. For itself is a special command, similar to a special command interpreter. Because its functional implementation requires execution of multiple statements, it must also have the function of analyzing and processing the command line (specifically referring to the command line after do). When command/cmd implements for, it will naturally borrow its own original command line analysis module. Therefore, for has the characteristic of secondary escape. The statements after do in for are analyzed and interpreted in two levels. The first level is read in command/cmd and interpreted in for command line, and the second level is read in for and interpreting the do command, it usually explains the same command line multiple times.

Then, we can notice that when using command line parameter variables and environment variables in do, double % is not needed, because these variables are replaced with specific unchanged string constants after being escaped at the first level, and participate in all execution processes of the for loop; while alternative variables require constant dynamic changes during execution (in the subcommand line after do), and this change naturally still needs to be implemented through escape characters, so using double % is an inevitable choice.

In addition, it should be noted that when using for in the command line, it does not require double % because the command interpreter handles the command line and batch processing differently. In earlier DOS versions, % was not considered an escape character in the command line, so it will not be escaped or escaped, so it was impossible to directly reference environment variables on the command line at that time. When using for, only one % is needed for for escape and escape. In later versions of the command interpreter, support for command line escape (mainly support for environment variables), but the tradition of using single % of the command line is still retained.

The delayed replacement of variables in cmd is a special case, but it does not violate the above escape principle, but the environment variables in for are no longer constants.