windows 每个批处理脚本运行后如何清除变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13727125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear variables after each batch script run?
提问by ttback
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.
似乎因为我使用 SET 在批处理脚本中声明我的变量,如果我在 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?
在不关闭 CMD 的情况下,我是否必须使用 setlocal 和 endlocal 来确保一次运行中的变量不会持续到另一次运行?
回答by dbenham
Yes, you should use SETLOCAL. That will localize any changes such that the old environment will be restored once ENDLOCAL is issued.
是的,您应该使用 SETLOCAL。这将本地化任何更改,以便在发出 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)
此外,如果您的脚本(或例程)被调用,那么当 CALL 完成时,对于在被调用例程中发出的每个活动 SETLOCAL 都有一个隐式 ENDLOCAL。无需将 ENDLOCAL 放在例程的末尾,(虽然它不会造成伤害)
For example
例如
@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
output:
输出:
var=pre-CALL value
var=within CALL value
var=pre-CALL value
ENDLOCAL within a CALLed routine will never rollback a SETLOCAL that was issued before the CALL. For example.
CALLed 例程中的 ENDLOCAL 永远不会回滚在 CALL 之前发出的 SETLOCAL。例如。
@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
Result:
结果:
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