为什么设置批处理脚本变量会延迟? [英] Why is setting a batch script variable delayed?
问题描述
如何解决延迟变量分配?
How do I solve delayed variable assignment?
(我正在编造术语延迟变量分配",因为它看起来像是一个合理的描述性短语).
示例批处理脚本代码script.bat:
Example Batch Script Code script.bat:
@echo off
set mylocation=%CD%
echo mylocation %mylocation%
echo CD %CD%
实际输出
C:> script.bat
mylocation
CD C:\
C:>
我想要它做(或认为会做)
What I want it to do (or thought it would do)
C:> script.bat
mylocation C:\
CD C:\
C:>
编辑(更改):如果脚本结束后我在命令提示符中回显%mylocation%,则它具有一个值.
Edit (changed): If I echo %mylocation% in command prompt after the script ends it has a value.
C:>echo %mylocation%
C:\
C:>
这是原始代码,您可以观看YouTube视频 https://youtu.be/jQzEFD3yISA-在这里我尝试显示尽可能多的细节,以便所有内容都是准确的.
This is the original Code, and you can view the youtube video https://youtu.be/jQzEFD3yISA - where I try to show as much detail as possible so that, everything is exact.
@echo off
set natasha_command=%1
if %natasha_command% == start (
set mylocation=%CD%
echo mylocation %mylocation%
echo CD %CD%
)
goto :eof
推荐答案
在块语句(a parenthesised series of statements)
中,解析整个块并然后执行.块中的任何%var%
都将在解析该块时被该变量的值取代-在执行该块之前-相同的情况适用于FOR ... DO (block)
.
Within a block statement (a parenthesised series of statements)
, the entire block is parsed and then executed. Any %var%
within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block)
.
因此,IF (something) else (somethingelse)
将在遇到IF
时使用%variables%
的值执行.
Hence, IF (something) else (somethingelse)
will be executed using the values of %variables%
at the time the IF
is encountered.
克服此问题的两种常见方法是:1)使用setlocal enabledelayedexpansion
并使用!var!
代替%var%
来访问更改后的var
值,或2)调用子例程以使用更改值.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion
and use !var!
in place of %var%
to access the changed value of var
or 2) to call a subroutine to perform further processing using the changed values.
因此请注意使用CALL ECHO %%var%%
来显示更改后的var
值. CALL ECHO %%errorlevel%%
显示,但遗憾的是会显示RESETS错误级别.
Note therefore the use of CALL ECHO %%var%%
which displays the changed value of var
. CALL ECHO %%errorlevel%%
displays, but sadly then RESETS errorlevel.
这篇关于为什么设置批处理脚本变量会延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!