如何在每个批处理脚本运行后清除variables?

看来,因为我用SET来声明我的variables在批处理脚本中,如果我运行多次在CMD中,variables值将保持,除非我明确重置它们。

我是否必须使用setlocal和endlocal来确保一次运行的variables不会持续到另一次,而不closuresCMD?

是的,你应该使用SETLOCAL。 这将使本地化的任何变化,一旦ENDLOCAL发布后,旧的环境将被恢复。

当所有脚本处理完成并返回到命令行上下文时,会为每个活动的SETLOCAL颁发一个隐式ENDLOCAL。 没有必要明确地发出ENDLOCAL。

另外,如果您的脚本(或例程)被调用,那么当CALL完成时,对于在CALLed例程中发出的每个活动SETLOCAL都有一个隐式的ENDLOCAL。 不需要在例程结束时放置ENDLOCAL(尽管它不会受到伤害)

例如

@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 

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 

结果:

 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