我有简单的 cmd 脚本:
@echo off
if %1.==. (
echo Missing argument
) else (
SET somevar=%1
echo %1
echo %somevar%
)
问题是它看起来像变量 somevar
的回显else block 在设置变量之前运行。每次我运行此命令时,参数的回显工作正常,但变量的回显显示上次运行的值。这种情况只发生在 if/else block 中,我不明白为什么。如果我这样修改脚本:
@echo off
if %1.==. (
echo Missing argument
exit /B
)
SET somevar=%1
echo %1
echo %somevar%
结果正如我所料。使用不同的参数交替运行脚本可以清楚地看到问题。
我读过一些帖子,例如。 How to clear variables after each batch script run?但我认为这是不同类型的问题。
那么,有什么方法可以防止 IF/ELSE 语句中出现此类行为吗?
最佳答案
@echo off
if %1.==. (
echo Missing argument
) else (
SET somevar=%1
echo %1
CALL echo %%somevar%%
)
或
@echo off
SETLOCAL EnableDelayedExpansion
if %1.==. (
echo Missing argument
) else (
SET somevar=%1
echo %1
echo !somevar!
)
资源(必读):
- (命令引用)An A-Z Index of the Windows CMD command line
- (其他细节)Windows CMD Shell Command Line Syntax
- (特殊页面)EnableDelayedExpansion
- (
CALL echo %%somevar%%
) (note doubled percent signs) - (不是
%1%
,而是%1
)Command Line arguments (Parameters)
关于windows - 在 Windows CMD 批处理文件中的 IF/ELSE 语句内设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56599132/