如何清除每个批处理脚本运行后的变量?(How to clear variables after ea

2019-08-03 13:50发布

看来,因为我使用SET声明我的变量批处理脚本,如果我在cmd中多次运行它,变量值将持续,除非我明确地重置。

我一定要使用SETLOCAL和ENDLOCAL,以确保从一个运行变量不会保留到另一个,而无需关闭CMD?

Answer 1:

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

当所有的脚本处理结束,并返回到命令行下,没有为每个活跃SETLOCAL颁发的隐ENDLOCAL。 有没有必要明确地发出ENDLOCAL。

另外,如果您的脚本(或程序)被调用,然后调用完成时,有该被调用的程序中发出的每一个活跃的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

被调用函数内ENDLOCAL永远不会回滚在调用之前发出一个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


文章来源: How to clear variables after each batch script run?