2007-12-13

BAT Files vs. Variable Expansion

You might think that the following BAT script would print out the word right:

set answer=wrong
if "a" == "a" (
    set answer=right
    echo %answer%
)

... but it actually prints out wrong.  The reason is that the BAT processor expands the variable answer when it is read, not when it is executed.  To work around this problem, you must use an extension, thus:

setlocal enabledelayedexpansion
set answer=wrong
if "a" == "a" (
    set answer=right
    echo !answer!
)

Note the use of exclamation marks instead of percent signs to delimit the delayed expansion of the variable answer.