TExcelTAD
Home › Windows CMD & Batch › setlocal & Delayed Expansion

setlocal & Delayed Expansion

Two commands at the top of a batch file change how all its variables behave: setlocal keeps the script's variables from leaking into the Command Prompt, and enabledelayedexpansion fixes the most confusing behaviour of CMD, variables inside loops and blocks that seem to never change. Most well-written batch files start like this:

cmd
@echo off
setlocal enabledelayedexpansion

setlocal: variables that don't leak

By default, every set in a batch file changes the environment of the Command Prompt that ran it. Run a script twice and the second run sees leftovers from the first; run two scripts in a row and one sees the other's variables.

setlocal takes a snapshot of the environment. When the script ends (or endlocal runs), every change since the snapshot is undone: new variables vanish, changed variables get their old values back, and even the current directory is restored.

cmd · try it yourself
@echo off
set "shared=outer value"
setlocal
set "shared=changed inside"
set "only_inside=temporary"
mkdir work
cd work
echo inside:  shared=%shared%, only_inside=%only_inside%, dir=%CD%
endlocal
echo outside: shared=%shared%, only_inside=%only_inside%, dir=%CD%
inside:  shared=changed inside, only_inside=temporary, dir=C:\Users\learner\work
outside: shared=outer value, only_inside=, dir=C:\Users\learner

setlocal blocks can be nested; each endlocal closes the most recent one. Anything still open is closed automatically when the batch file ends, so a single setlocal at the top is enough to keep a script tidy.

The problem: expansion happens when a line is read

CMD processes each command in two broad steps: first it reads and expands the line, replacing every %var% with its value, and only then it executes it. For a simple line that's invisible. But a parenthesised block (an if body or a for body, even across many lines) counts as one command. All of its %var% references are replaced once, before any of it runs:

cmd · try it yourself
@echo off
set /a count=0
for %%f in (a b c) do (
  set /a count+=1
  echo item %%f, count is %count%
)
echo after the loop: %count%
item a, count is 0
item b, count is 0
item c, count is 0
after the loop: 3

The set /a really did run three times, as the last line proves. But %count% inside the block had already been replaced by 0 when the loop started. This is the source of countless "my variable doesn't update" questions.

The fix: !var! with enabledelayedexpansion

setlocal enabledelayedexpansion enables a second syntax: !var! is expanded when the command actually runs, not when the block is read:

cmd · try it yourself
@echo off
setlocal enabledelayedexpansion
set /a count=0
for %%f in (a b c) do (
  set /a count+=1
  echo item %%f, count is !count!
)
echo after the loop: %count%
item a, count is 1
item b, count is 2
item c, count is 3
after the loop: 3

Rule of thumb: inside a block, read a variable that changes in the same block with !var!. Outside blocks, or for values that don't change, %var% is fine.

The same applies to if blocks:

cmd · try it yourself
@echo off
setlocal enabledelayedexpansion
set "status=idle"
if exist "%~f0" (
  set "status=running"
  echo percent:  %status%
  echo exclaim:  !status!
)
percent:  idle
exclaim:  running

Building strings in a loop

Delayed expansion makes accumulation patterns work, such as joining items into one string:

cmd · try it yourself
@echo off
setlocal enabledelayedexpansion
set "list="
for %%x in (red green blue) do (
  if defined list (set "list=!list!, %%x") else (set "list=%%x")
)
echo colours: !list!
colours: red, green, blue

It also makes dynamic names and string operations with variable positions possible, because % is expanded first and ! second:

cmd · try it yourself
@echo off
setlocal enabledelayedexpansion
set "day_1=Mon"
set "day_2=Tue"
set "day_3=Wed"
for /l %%i in (1,1,3) do echo %%i = !day_%%i!
set "word=keyboard"
for /l %%i in (0,1,2) do echo prefix %%i: !word:~0,%%i!
1 = Mon
2 = Tue
3 = Wed
prefix 0:
prefix 1: k
prefix 2: ke

In !day_%%i! the loop variable is substituted first, giving !day_1!, which is then expanded. This is how batch files simulate arrays.

The catch: ! in your data

With delayed expansion on, ! is special everywhere, including in text that comes from files, file names and variables. A lone ! disappears, and text between two ! is treated as a variable name:

cmd
C:\Users\ada>type bang.bat
@echo off
> msg.txt echo Hello world!
echo --- off:
for /f "delims=" %%l in (msg.txt) do echo %%l
setlocal enabledelayedexpansion
echo --- on:
for /f "delims=" %%l in (msg.txt) do echo %%l
endlocal

C:\Users\ada>bang.bat
--- off:
Hello world!
--- on:
Hello world

With delayed expansion on, the ! coming from the file is swallowed. (This one is shown as a plain session because the playground's cmd engine, Wine, keeps the ! here, unlike Windows.)

The usual remedy is to enable delayed expansion only where it's needed: keep it off while you read the %%l value into a variable, then turn it on to use the variable (!line! expansion doesn't re-scan the result for more !):

cmd · try it yourself
@echo off
> msg.txt echo Wow! Great!
for /f "delims=" %%l in (msg.txt) do (
  set "line=%%l"
  setlocal enabledelayedexpansion
  echo safe: !line!
  endlocal
)
safe: Wow! Great!

Each setlocal inside the loop is closed by the matching endlocal in the same pass. Don't leave them open: CMD allows only a limited nesting depth.

Getting a value out of setlocal

Because endlocal throws away every change, returning a result needs a trick. CMD expands %var% on a line before running it, so this works:

cmd · try it yourself
@echo off
call :make_id ada result
echo id: %result%
goto :eof

:make_id
setlocal
set "base=%~1"
set /a stamp=4200+7
set "id=user-%base%-%stamp%"
endlocal & set "%~2=%id%"
goto :eof
id: user-ada-4207

When CMD reads the line endlocal & set "result=%id%", %id% is replaced with user-ada-4207 while the local variables still exist. Then endlocal runs and the set stores the already-expanded text in the caller's environment.

setlocal enableextensions

The other option you'll see is setlocal enableextensions. Command extensions (set /a, if defined, for /f, %~dp0, goto :eof, ...) are on by default on every modern Windows, so this is mostly a defensive habit. You can combine both: setlocal enableextensions enabledelayedexpansion.

Statement Effect
setlocal start a local scope for variables and the current directory
setlocal enabledelayedexpansion the same, and !var! is expanded at run time
setlocal disabledelayedexpansion local scope with ! as an ordinary character
endlocal end the most recent scope; changes are undone

Comparison with other shells

Bash and PowerShell don't have this problem: they evaluate $var when each command runs, even inside loops. Their closest relatives to setlocal are local variables in Bash functions and PowerShell's automatic scopes, and running code in a subshell ( ... ) in Bash.

Learn more: Bash Functions, PowerShell Scripts & Scopes, Batch for Loops.

Test yourself

Inside a for loop, set /a n+=1 runs, but echo %n% in the same loop always prints the starting value. Why?

  1. set /a doesn't work in loops
  2. %n% was expanded once when the whole loop block was read
  3. Loops create a copy of n
  4. echo caches its output

What does endlocal do?

  1. Deletes all environment variables
  2. Undoes the variable and directory changes made since the matching setlocal
  3. Ends the batch file
  4. Disables delayed expansion only

Why does endlocal & set "r=%x%" keep the value of x?

  1. endlocal ignores variables named on the same line
  2. %x% is expanded when the line is read, before endlocal runs
  3. set runs before endlocal
  4. It doesn't keep it