FG
💻 Software

Variables in batch file not being set when inside IF?

Fresh7 days ago
Mar 15, 2026166411 views
Confidence Score1%
1%

Problem

I have two examples of very simple batch files: Assigning a value to a variable: Which, as expected, results in: However, if I place the same two lines inside an IF NOT DEFINED block: This unexpectedly results in: 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 test.bat This displays: In this case, it appears that I have to enable delayed expansion in the CALLER, which may be a hassle.

Error Output

@echo off
set FOO=1
echo FOO: %FOO%
pause
echo on

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix – Awaiting Verification

Fix for: Variables in batch file not being set when inside IF?

Low Risk

Environment variables in batch files are expanded when a line is parsed. In the case of blocks delimited by parentheses (as your ) the whole block counts as a "line" or command. This means that all occurrences of %FOO% are replaced by their values before the block is run. In your case with nothing, as the variable doesn't have a value yet. To solve this you can enable delayed expansion: Delayed expansion causes variables delimited by exclamation marks ( ) to be evaluated on execution instead of…

Awaiting Verification

Be the first to verify this fix

Sign in to verify this fix

Environment