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?
Assignments (i.e. set statements) made within an if block are not realized until after
Share
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:
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:
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:
…is wrong because %var% value is expanded just once before executing the whole IF (or FOR). You must use:
Type SET /? for further details.