-1

I am trying to learn MS Batch, and I was specifically trying to understand the setlocal and the enabledelayedexpression aspects, when I came across vocabulary I did not understand: execution time and parse time

1 Answer 1

5

The parser has different phases, when parsing a single line.
So the percent expressions are all expand when a line or block is parsed, before the line (or any line in a block) is executed.

So at execution time they can't change anymore.

set var=origin
echo #1 %var%
(
  set var=new value
  echo #2 %var%
)
echo #3 %var%

It outputs

#1 origin
#2 origin
#3 new value

As at parse time #2 will be expanded to origin before any line of the block is executed. So you can see the new value just after the block at #3.

In contrast, delayed expansion is expanded for each line just before the line is executed.

setlocal EnableDelayedExpansion
set var=origin
echo #1 %var%, !var!
(
  set var=new value
  echo #2 %var%, !var!
)
echo #3 %var%, !var!

Output

#1 origin, origin
#2 origin, new value
#3 new value, new value

Now at #2 you see two different expansions for the same variable, as %var% is expanded when the block is parsed, but !var! is expanded after the line set var=new value was executed.

More details about the batch parser at SO: How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Not the answer you're looking for? Browse other questions tagged or ask your own question.