Why, if I put an odd amount of% s in the processed FOR elements, does the command exit the script?

Here is an example:

@echo off for /f %%# in ('rem %') do echo %%# echo never displayed 

(and this result is slightly different from this example - one empty less line is created, despite the fact that scripts should do the same)

 @echo off for /f %%# in ('rem %') do echo %%# echo never displayed 

Although there is no problem if there are no tokens in the DO block:

 @echo off for /f %%# in ('rem %') do dir echo will be displayed 

It looks like the script is trying to expand some variable when it encounters % , but is somehow interrupted by a closing bracket?

+5
source share
2 answers

This is a parser error when trying to interpret a string

 for /f %%# in ('rem %') do echo %%# ^...........^ undefined variable for /f %%# in ('rem %') do dir ^ without a closing percent sign, it is discarded 

Try it (it does not work)

 for /f %%# in ('echo yes ^& rem %') do echo %%# 

And now with

 set "') do echo =') do echo %%" for /f %%# in ('echo yes ^& rem %') do echo %%# echo displayed 

edited after some test, it seems that the problem is not with the for command, but with the search for the right closing parenthesis, which ends with improper error handling, which discards all commands processed inside an open code block.

This batch file (all these are lines)

 if 1==1 ( for %a in (test) do echo %%a 

will fail with a syntax error ( %a ) indicating that the parser is processing it, but if the error is fixed

 if 1==1 ( for %%a in (test) do echo %%a 

the party ends without errors

Just a simple batch like this, without the difference of an if or for analyzer, behaves the same

 ( echo test 
+5
source

The character '%' must be escaped by another character '%'. Should you use '#' for the variable name? [Az] doesn't work for you?

 @echo off for /f %%# in ('rem %%') do echo %%# echo never displayed 
+1
source

Source: https://habr.com/ru/post/1234801/


All Articles