1

I met a weird problem during write some Windows batch script: the iterator value %%X got changed between echo and set in the for loop. Here is the code:

@echo off

for %%x in (%*) do (
    echo %%x
    set path1=%%x
    echo %path1%

)

@echo on

when invoke this script:

c:\> test.bat aaa bbb

the result is:

aaa
bbb
bbb
bbb

the first bbb is %path1%. Could not understand why this value is different from %%X

Could anyone help? Thanks.

Stephan
  • 53,940
  • 10
  • 58
  • 91
cao lei
  • 891
  • 1
  • 9
  • 19

1 Answers1

1

The point is that usually your variables are expanded before your code runs so the first value assigned to path1 will remain till the end. To avoid this you have to add SETLOCAL ENABLEDELAYEDEXPANSION at the beginngin of your code and access path1 with !path1! instead of %path1%:

@echo off
setlocal EnableDelayedExpansion

for %%x in (%*) do (
    echo %%x
    set path1=%%x
    echo !path1!

)

@echo on

This will force the interpreter to re-evaluate the value of path1 at run time.

Check http://ss64.com/nt/delayedexpansion.html for more information.

MichaelS
  • 5,941
  • 6
  • 31
  • 46