Reputation: 289
Assignments (i.e. set statements) made within an if block are not realized until after the if block. So, in other words, you can't rely on variable assignment within an if block. How to fix this?
Upvotes: 1
Views: 104
Reputation: 67216
Assignments in IF or FOR blocks are realized immediately. What is not properly realized is the sustitution of variable values enclosed in percent signs. You must note that a %variable% value is replaced before executing the line. For example:
set var=Old value
set var=New value & echo %var%
Previous commands show: "Old value". The way to solve this problem is via Delayed Expansion, that is, enclose the variable in exclamation marks instead percents and add a setlocal ... command at beginning. That is:
setlocal EnableDelayedExpansion
set var=Old value
set var=New value & echo !var!
This way, !var! value is replaced until echo !var! command is executed (delayed expansion) and after the previous set command is executed, so previous commands show: "New value".
This same dicussion apply to any variable inside parentheses. For example:
set var=Old value
if 1 == 1 (
set var=New value
echo %var%
)
...is wrong because %var% value is expanded just once before executing the whole IF (or FOR). You must use:
setlocal EnableDelayedExpansion
set var=Old value
if 1 == 1 (
set var=New value
echo !var!
)
Type SET /? for further details.
Upvotes: 2