I've seen SETLOCAL ENABLEDELAYEDEXPANSION & SETLOCAL DISABLEDELAYEDEXPANSION in many batch files but what do the commands actually do?
-
3Possible duplicate of [SETLOCAL and ENABLEDELAYEDEXPANSION usage question](http://stackoverflow.com/questions/6679907/setlocal-and-enabledelayedexpansion-usage-question) – Divi May 13 '16 at 04:12
4 Answers
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.
- 77,302
- 8
- 62
- 84
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
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
)
- 55,367
- 18
- 148
- 187
ALSO note that with SETLOCAL ENABLEDELAYEDEXPANSION you cant echo !!!!!! so:
echo my sentence! 123
will be outputed as:
my sentence 123
- 124,011
- 12
- 67
- 124