Here's a sample:
D:\>set var=123
D:\>set var=456 & echo %var%
123
D:\>set var=789 & echo %var%
456
A new value is set in var variable, but echo still displays an old value.
Anyone have a clue as to what happened? And how to get correct value?
When execution of a command or block of commands (commands concatenated or enclosed in parenthesis) is requested, the parser replaces all read operations on variables with the content in the variable before starting to execute the commands/block
In your case, the value in the variable is changed at execution time, but the value to echo
to console was determined before the change was made. This can be tested with
set "var=abc"
set "var=123" & set var & echo %var%
set var
will show you the correct value in the variable (in this command there was no variable read operation to be replaced by the parser) but echo
will show the old value (replaced by the parser before command execution).
Inside batch files, the usual way to handle it is to use delayed expansion (setlocal enabledelayedexpansion
command), that will allow you to change, where needed, the syntax to access variables from %var%
into !var!
, indicating to the parser that the read operation must be delayed until the command is executed.
BUT you can not enable delayed expansion from command line. Maybe it is enabled (not the default state) and you will be able to use it
set "var=abc"
set "var=123" & echo !var!
But as said, this is not the usual case. You will need to escape the percent signs to hide the variable from the parser and force a second parser evaluation of the line.
set "var=abc"
set "var=123" & call echo ^%var^%
Or you can spawn a separate cmd
instance with delayed expansion enabled
set "var=abc"
set "var=123" & cmd /v /c"echo !var!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With