Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.
%0 is the name of the batch file. %~n0 Expands %0 to a file Name without file extension.
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.
var2 is set, but the expansion in the line echo %var2%
occurs before the block is executed.
At this time var2
is empty.
Therefore the delayedExpansion syntax exists, it uses !
instead of %
and it is evaluated at execution time, not parse time.
Please note that in order to use !
, the additional statement setlocal EnableDelayedExpansion
is needed.
setlocal EnableDelayedExpansion
set var1=true
if "%var1%"=="true" (
set var2=myvalue
echo !var2!
)
I am a bit late to the party but another way to deal with this condition is to continue process outside if
, like this
set var1=true
if "%var1%"=="true" (
set var2=myvalue
)
echo %var2%
Or/and use goto
syntax
set var1=true
if "%var1%"=="true" (
set var2=myvalue
goto line10
) else (
goto line20
)
. . . . .
:line10
echo %var2%
. . . . .
:line20
This way expansion occurs "in time" and you don't need setlocal EnableDelayedExpansion
. Bottom line, if you rethink design of your script you can do it like that
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