What is meant by "variable expansion"? Does it mean simply "variable definition", or something else?
What happens when I say setLocal EnableDelayedExpansion
? Google wasn't clear.
Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command. Variable expansion means replacing a variable (e.g. %windir%) with its value C:\WINDOWS.
Variable expansion is the term used for the ability to access and manipulate values of variables and parameters. Basic expansion is done by preceding the variable or parameter name with the $ character. This provides access to the value.
setlocal ENABLEDELAYEDEXPANSION ENABLEEXTENSIONSset variable modifications local to this script, i.e., the change to variable value disappears after the script ends. The variables revert to their original values. Without setlocal, the changes of variables preserves even after the bat script exits.
%
or !
by its value.%normal%
expansion happen just once, before a line is executed. This means that a %variable%
expansion have the same value no matters if the line is executed several times (like in a for
command).!delayed!
expansion is performed each time that the line is executed.See this example:
@echo off
setlocal EnableDelayedExpansion
set "var=Original"
set "var=New" & echo Normal: "%var%", Delayed: "!var!"
Output:
Normal: "Original", Delayed: "New"
Another one:
@echo off
setlocal EnableDelayedExpansion
set "var1=Normal"
set "var2=Delayed"
for /L %%i in (1,1,10) do (
set "var1=%var1% %%i"
set "var2=!var2! %%i"
)
echo Normal: "%var1%"
echo Delayed: "%var2%"
Output:
Normal: "Normal 10"
Delayed: "Delayed 1 2 3 4 5 6 7 8 9 10"
Normal expansion is not necessarily a disadvantage, but depends on the specific situation it is used. For example, in any other programming languages, to exchange the value of two variables you need the aid of a third one, but in Batch it can be done in just one line:
set "var1=%var2%" & set "var2=%var1%"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With