
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 var2
?var1
답변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%
- 배치 파일에서 사용되는 경우 변수는 null 문자열로 대체됩니다.
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]
같은 줄에서 "echo var2"를 수행하기 위해 두 번째 "for" 루프를 추가할 수도 있습니다.
: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.