72
24
I have two examples of very simple batch files:
Assigning a value to a variable:
@echo off
set FOO=1
echo FOO: %FOO%
pause
echo on
Which, as expected, results in:
FOO: 1
Press any key to continue . . .
However, if I place the same two lines inside an IF NOT DEFINED block:
@echo off
IF NOT DEFINED BAR (
set FOO=1
echo FOO: %FOO%
)
pause
echo on
This unexpectedly results in:
FOO:
Press any key to continue . . .
This shouldn't have anything to do with the IF, clearly the block is being executed. If I define BAR above the if, only the text from the PAUSE command is displayed, as expected.
What gives?
Follow up question: Is there any way to enable delayed expansion without setlocal?
If I were to call this simple example batch file from inside another, the example sets FOO, but only LOCALLY.
For example:
testcaller.bat
@call test.bat
@echo FOO: %FOO%
@pause
test.bat
@setlocal EnableDelayedExpansion
@IF NOT DEFINED BAR (
@set FOO=1
@echo FOO: !FOO!
)
This displays:
FOO: 1
FOO:
Press any key to continue . . .
In this case, it appears that I have to enable delayed expansion in the CALLER, which may be a hassle.
18And if you need to echo an
!
, use^^^!
(escape it twice). Otherwise the "delayed expansion" feature will eat it. – user1686 – 2009-12-04T13:32:02.403