File test.cmd:
name=dummy
for /f "eol=; tokens=1 delims=," %%i in (list.txt) do (
echo i: %%i
set name=%%i
echo name: %name%)
the file list.txt contains this lines (one name per line):
John
Tom
Erica
Sara
Each time I launch this batch I get this output:
i: John
name: dummy
i:T om
name: dummy
i: Erica
name: dummy
i: Sara
name: dummy
It seems that the variable name does not get assigned the value of %%i
Any idea?
You’re falling into the old trap of not using delayed expansion.
For a quick fix, just put
before that loop in your batch file and use
!name!instead of%name%.CMD expands variables while parsing a command. A command in this sense is a single line or a “block”, delimited with parentheses. The complete
forloop is only parsed once and in that stage%name%gets replaced with the value it has at that point, namely"dummy". Delayed expansion on the other hand uses!instead of%to delimit variable names and the variables then get expanded right before execution of a command.Whenever you are setting a variable inside a parenthesized block and use its value in the same block again you need to use delayed expansion.
help sethas also some info about this: