24

I've seen SETLOCAL ENABLEDELAYEDEXPANSION & SETLOCAL DISABLEDELAYEDEXPANSION in many batch files but what do the commands actually do?

1

4 Answers 4

27

enabledelayeexpansion instructs cmd to recognise the syntax !var! which accesses the current value of var. disabledelayedexpansion turns this facility off, so !var! becomes simply that as a literal string.

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Using !var! in place of %var% accesses the changed value of var.

7

Copied from How do you use SETLOCAL in a batch file? (as dbenham indicated in his first comment).

Suppose this code:

If "%getOption%" equ  "yes" (
   set /P option=Enter option: 
   echo Option read: %option%
)

Previous code will NOT work becase %option% value is replaced just one time when the IF command is parsed (before it is executed). You need to "delay" variable value expansion until SET /P command had modified variable value:

setlocal EnableDelayedExpansion
If "%getOption%" equ  "yes" (
   set /P option=Enter option: 
   echo Option read: !option!
)

Check this:

set var=Before
set var=After & echo Normal: %var%  Delayed: !var!

The output is: Normal: Before Delayed: After

1

With delayed expansion you will able to access a command argument using FOR command tokens:

setlocal enableDelayedExpansion
set /a counter=0
for /l %%x in (1, 1, 9) do (
 set /a counter=!counter!+1
 call echo %%!counter! 
)
endlocal

Can be useful if you are going to parse the arguments with for loops

It helps when accessing variable through variable:

 @Echo Off
 Setlocal EnableDelayedExpansion
 Set _server=frodo
 Set _var=_server
 Set _result=!%_var%!
 Echo %_result%

And can be used when checking if a variable with special symbols is defined:

setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! ( 
   echo has NOT admin permissions
) else (
   echo has admin permissions
)
0

ALSO note that with SETLOCAL ENABLEDELAYEDEXPANSION you cant echo !!!!!! so:

echo my sentence! 123

will be outputed as:

my sentence 123

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.