Alex Rivera | Logout

Batch file fails to set environment variable within conditional statement

Asked 2009-05-18T11:21:25.457
15

Why does the following Windows Batch File output Foo followedby Bar, rather than Baz?

@echo off
setlocal

set _=Foo
echo %_%
set _=Bar
if 1==1 (
    set _=Baz
    echo %_%
)

The output on my system (Microsoft Windows XP [Version 5.1.2600]) is:

Foo
Bar

If I remove the conditional statement, the expected output of Foo and Baz is observed.

Edit
Report

1 Answer

4

The answer to this is the same as the answer to:Weird scope issue in batch file. See there for more details. Basically variable expansion is done at line read time, not at execution time.

answered 2009-05-18T11:42:33.790

Your Answer