Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch files: what is variable expansion, and what does EnableDelayedExpansion mean?

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.

like image 984
Aviv Cohn Avatar asked Aug 15 '14 09:08

Aviv Cohn


People also ask

What is Enabledelayedexpansion in batch file?

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.

What does expanding a variable mean?

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.

What is Setlocal Enableextensions Enabledelayedexpansion?

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.


1 Answers

  • Variable expansion means replace a variable enclosed in % or ! by its value.
  • The %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).
  • The !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%"
like image 104
Aacini Avatar answered Sep 17 '22 16:09

Aacini