我有一个像这样的批处理脚本:
@echo off
setlocal
some commands to set variable %equal%
if %equal%==no (
some commands to set variable %equall% (including a call to a separate batch file)
if %equall%==no (
other commands (including a call to a separate batch file)
)
) else (
echo nothing new
)
endlocal
exit /b
但是我收到了这个错误(翻译自西班牙语,所以它可能是真空的):"(" was not expected at this moment
在第一个if句子上。
但是,如果我删除内部if条件,它运行正常....
我缺少什么?
答案 0 :(得分:2)
您遇到delayed expansion问题。变量equall
在代码块中定义,因此仍未定义%equall%
。那就是你的行
if %equall%==no (
被解析为
if ==no (
导致上述错误"(" is unexpected at this time"
要更正此问题,请使用setlocal enabledelayedexpansion
命令启用延迟扩展,并使用!
语法代替%
使用延迟扩展语法:
setlocal enabledelayedexpansion
if 1==1 (
set "var=hello"
echo !var!
)
此外,您应该习惯使用if
更好的语法(引用比较的两边):
if "%var%" == "value" ...
(或延迟扩展:if "!var!% == "value"
)即使变量为空,也会将其解析为:
if "" == "value" ...
这是完全有效的语法。
答案 1 :(得分:0)
我使用了一种解决方法,即将外部if中的所有内容发送到标签:
@echo off
setlocal
some commands to set variable %equal%
if %equal%==no (
goto :label
) else (
echo nothing new
)
endlocal
exit /b
:label
some commands to set variable %equall% (including a call to a separate batch file)
if %equall%==no (
other commands (including a call to a separate batch file)
)