Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file fails to set environment variable within conditional statement

Tags:

batch-file

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.

like image 487
Daniel Fortunov Avatar asked May 18 '09 11:05

Daniel Fortunov


1 Answers

What's happening is that variable substitution is done when a line is read. What you're failing to take into account is the fact that:

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

is one "line", despite what you may think. The expansion of "%_%" is done before the set statement.

What you need is delayed expansion. Just about every single one of my command scripts starts with "setlocal enableextensions enabledelayedexpansion" so as to use the full power of cmd.exe.

So my version of the script would be:

@echo off
setlocal enableextensions enabledelayedexpansion

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

endlocal

This generates the correct "Foo", "Baz" rather than "Foo", "Bar".

like image 97
paxdiablo Avatar answered Oct 05 '22 03:10

paxdiablo