在一行批处理中设置变量

在一行批处理中设置变量
set var1=Demo
set var2=%var1%
echo %var2%
rem Output:Demo

为什么set var2如果在一行中则不起作用set var1

set var1=& set var2=
set var1=Demo& set var2=%var1%
echo %var2%
rem output:%var1%

我怎样才能set var2var1一行中?

答案1

set var2为什么如果在一行中不起作用set var1

作为哈里麦克指出:

变量替换是在执行命令行之前对整个命令行进行的。此时变量var1尚未定义。

您可以使用延迟扩展来解决这个限制:

@echo off
setlocal enabledelayedexpansion
set var1=Demo & set var2=!var1!
echo %var2%
endlocal

例子:

F:\test>test
Demo

进一步阅读

答案2

变量替换是在执行命令行之前对整个命令行进行的。此时变量var1尚未定义。

未定义变量替换的规则是:

  • 如果变量是交互输入的,则不进行替换,文本保持不变%var1%
  • 如果在批处理文件中使用,该变量将被空字符串替换。

您需要将这一行代码分成两行才能var1 获得值。或者查看@DavidPostill 的回答。

答案3

您可以在不使用延迟扩展(不带“ setlocal enabledelayedexpansion”)的情况下通过使用带有“call”的“for”(循环)来实现此目的。

@echo off
set "var1=" & set "var2="
echo var1=[%var1%], var2=[%var2%]

:rem The one-liner: 
set "var1=Demo" & for /f "usebackq delims=" %%a in (`call echo ^%var1^%`) do @set "var2=%%a"
:: 

echo var1=[%var1%], var2=[%var2%]
:end

输出:

var1=[], var2=[]
var1=[Demo], var2=[Demo]

您甚至可以在同一行中添加第二个“for”循环来执行“echo var2”:

:rem The one-liner: 
set "var1=Demo" & for /f "usebackq delims=" %%a in (`call echo ^%var1^%`) do @set "var2=%%a" & for /f "usebackq delims=" %%a in (`call echo var2^=[^%var2^%]`) do @echo %%a
:: 
:end

“最终”输出:

var2=[Demo]

以下是“for”和“call”的细分:

for /f "usebackq" %%a    Operates on a command that is enclosed in `backquotes`. 
                         Executes that command and captures the output of that 
                         command into variable %%a. 

"delims="                Disables all delimiters when parsing the command 
                         output. Default delimiters are "space" and "tab". 
                         Not required for this specific example. 
                         Used when the command output might contain delimiters. 

(`call echo ^%var1^%`) 
(`call echo var2^=[^%var2^%]`) 
                         Use "call" to execute the echo command within a 
                         separate process. 

                         "^" escapes special characters like "%" and "=" when 
                         the command is read by "for". 

 do @set "var2=%%a" 
 do @echo %%a            Sets the variable "var2" from the output of the 
                         command in the for loop. 


                         In this case, the for command will execute just once. 

                         If the output of the command spanned multiple lines, 
                         the for command would execute once for each non-empty 
                         output line. 

相关内容