bat-variable delay

setlocal

Start the localization operation of the environment changes in the batch file. The environment changes after executing setlocal are limited to the batch file. Endlocal must be executed to restore the settings.

bat processing mechanism

set a=1

Read line by line, do preprocessing before execution, and expand the variable value to the actual value
set b=%a%
. During preprocessing,set b=1

The contents in parentheses such as if and for are processed as one statement instead of multiple statements
if %a%==1 (
set a=2
echo %a%
)
. During preprocessing,set a=2 & echo 1

Therefore, you need to use a variable delay to ensure that the next statement is run after the previous statement is run.

variable delay

// 开启变量延迟
setlocal enabledelayedexpansion
// 关闭变量延迟
setlocal disabledelayedexpansion

Variables must be used ! !, but % % cannot be used

Example

The running result is that ECHO is turned off.
The third line of preprocessing is set var2=1 & echo, which is equivalent to executing echo, so the result will output that ECHO is turned off.

@echo off 
set var1=1
set var2=%var1% & echo %var2%
pause

Line it up separately, run it one after another, use it % %, the running result is 1

@echo off 
set var1=1
set var2=%var1%
echo %var2%
pause

Run at the same time, add 变量延迟, use !!, the running result is 1

setlocal enabledelayedexpansion
@echo off 
set var1=1
set var2=%var1% & echo !var2!
pause

Guess you like

Origin blog.csdn.net/WEB___/article/details/128967677