问题描述
看来,因为我使用set声明我的变量批处理脚本,如果我在cmd中多次运行它,变量值将持续存在,除非我明确重置。
It seems that since I use SET to declare my variables in batch script, if I run it multiple times in cmd, the variable value will persist unless I explicitly reset them.
我必须使用SETLOCAL和ENDLOCAL,以确保从一个运行变量不会保留到另一个,而无需关闭CMD?
Do I have to use setlocal and endlocal to make sure the variables from one run doesn't persist over to another, without shutting down the CMD?
推荐答案
是的,你应该使用SETLOCAL。这将本地化的任何变化,例如,一旦ENDLOCAL发出的旧环境将得到恢复。
Yes, you should use SETLOCAL. That will localize any changes such that the old environment will be restored once ENDLOCAL is issued.
在所有的脚本处理结束并返回到命令行环境,对于每一个活动SETLOCAL发出一个隐含的ENDLOCAL。没有必要明确地发出ENDLOCAL
When all script processing finishes and you are returned to a command line context, there is an implicit ENDLOCAL issued for every active SETLOCAL. There is no need to explicitly issue ENDLOCAL.
另外,如果你的脚本(或程序)被调用,则调用完成时则表示这是在调用的例程中发出的每一个活动SETLOCAL一个隐含的ENDLOCAL。没有必要把ENDLOCAL在例行的结束,(尽管它不会伤害)
Also, if your script (or routine) is CALLed, then when the CALL completes there is an implicit ENDLOCAL for every active SETLOCAL that was issued within the CALLed routine. No need to put ENDLOCAL at end of a routine, (though it doesn't hurt)
例如
@echo off
set var=pre-CALL value
echo var=%var%
call :test
echo var=%var%
exit /b
:test
setlocal
set var=within CALL value
echo var=%var%
exit /b
输出:
var=pre-CALL value
var=within CALL value
var=pre-CALL value
被调用函数中ENDLOCAL永远不会回滚被调用之前发出SETLOCAL。例如。
ENDLOCAL within a CALLed routine will never rollback a SETLOCAL that was issued before the CALL. For example.
@echo off
setlocal
set var=VALUE 1
setlocal
set var=VALUE 2
echo before call: var=%var%
call :test
echo after call: var=%var%
endlocal
echo after endlocal: var=%var%
exit /b
:test
setlocal
set var=VALUE 3
echo within local CALL context: var=%var%
endlocal
echo within CALL after 1st endlocal: var=%var%
endlocal
echo within CALL cannot endlocal to before CALL state: var=%var%
exit /b
结果:
before call: var=VALUE 2
within local CALL context: var=VALUE 3
within CALL after 1st endlocal: var=VALUE 2
within CALL cannot endlocal to before CALL state: var=VALUE 2
after call: var=VALUE 2
after endlocal: var=VALUE 1
这篇关于如何清除每个批处理脚本运行后的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!