Batch file Windows批处理文件返回代码为';如果有';下面是一行
以下名为“foo.bat”的Windows批处理文件响应“退出”,并按预期将返回代码设置为1:Batch file Windows批处理文件返回代码为';如果有';下面是一行,batch-file,Batch File,以下名为“foo.bat”的Windows批处理文件响应“退出”,并按预期将返回代码设置为1: if "1"=="1" ( if "1"=="1" ( echo quitting exit /B 1 ) ) 但是,令我惊讶的是,此批处理文件的返回代码为0: if "1"=="1" ( if "1"=="1" ( echo quitting exit /B 1 ) echo anything ) 我在Windows命令提示符中确定批处理文件
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
)
但是,令我惊讶的是,此批处理文件的返回代码为0:
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
echo anything
)
我在Windows命令提示符中确定批处理文件的返回代码,如下所示:
> cmd.exe /c foo.bat
quitting
> echo %ERRORLEVEL%
0
我已经验证了我的环境中尚未设置ERRORLEVEL,运行set ERRORLEVEL
会按预期打印“环境变量ERRORLEVEL not defined”
关于第二个文件的所有其他内容都按预期工作。它只是呼应“退出”,而不是呼应“任何事情”。似乎向脚本添加echo anything
行意味着行exit/b1
仍然存在,但没有设置返回代码
这是EC2中的Windows7<代码>版本报告“Microsoft Windows[Version 6.1.7601]”
有没有办法确保
exit/b1
确实设置了返回代码,即使在复杂的if语句中也是如此?您的测试环境是什么?
您是否认为舒尔没有其他副作用
此批在Win7Ult和Win10pro中获得了预期的结果
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
ver > nul
Call :First
Echo called First ErrorLevel = %Errorlevel%
ver > nul
Call :Second
Echo called Second ErrorLevel = %Errorlevel%
Pause
Goto:Eof
:First
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
)
Goto :EoF
:Second
if "1"=="1" (
if "1"=="1" (
echo quitting
exit /B 1
)
echo anything
)
如果我将文件扩展名从“.bat”更改为“.cmd”,那么它的行为与预期的一样。我也遇到了同样的问题。我用这样的方法解决了这个问题:
if "1"=="1" (
if "1"=="1" (
echo quitting
goto Exit1
)
echo anything
)
goto :Eof
:Exit1
exit /b 1
另一个“已知”缺陷是:
rem t.bat
copy non-existing somewhere
rem
C:\> cmd /c t.bat
The system cannot find the file specified.
C:\> echo %errorlevel%
0
当使用cmd/c运行时,如果在批处理文件末尾有注释(或echo或通常不应更改errorlevel的内容),则在批处理文件末尾显式返回errorlevel不起作用。因此,我们需要使用此选项:
rem t.bat
copy non-existing somewhere
exit /b %errorlevel%
rem
C:\> cmd /c t.bat
The system cannot find the file specified.
C:\> echo %errorlevel%
1
我无法在Windows7和Windows10上重现这一点。你测试过你发布的代码吗?你是如何测试返回代码的?只是
回显%errorlevel%
?您没有手动设置errorlevel变量,是吗?我也无法重现您的结果。请显示调用“foo.bat”并测试返回的ERRORLEVEL的批处理脚本。如果测试是从命令行运行的,则显示显示错误结果的确切命令序列。还要验证您没有定义覆盖动态值的用户定义ERRORLEVEL环境变量(使用设置ERRORLEVEL
-您应该会收到环境变量ERRORLEVEL not defined
消息)。谢谢,我已经更新了答案。我已经展示了用于测试返回的ERRORLEVEL的命令,并且检查了ERRORLEVEL是否不是用户定义的。
rem t.bat
copy non-existing somewhere
exit /b %errorlevel%
rem
C:\> cmd /c t.bat
The system cannot find the file specified.
C:\> echo %errorlevel%
1