... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

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.


Blog Archive