批处理/命令脚本中的通常建议是使用exit /b
设置时退出ERRORLEVEL
来指示错误。然而这与 CMD 的配合不太好||
and &&
运营商。如果我在 CMD 命令行运行这些:
C:\>echo @exit /b 1 > foo.cmd
C:\>foo.cmd && echo success || echo fail
success
(预期输出是fail
).
据 ss64.com 报道 https://web.archive.org/web/20230315075002/https://ss64.com/nt/errorlevel.html这是因为“退出代码”和ERRORLEVEL
并不总是相同的exit
可以返回成功(0
) 以非 0 退出时的退出代码ERRORLEVEL, and exit code is what
||/
&&`正在关注。
有趣的是,添加call
使它按我的预期工作:
C:\>call foo.cmd && echo success || echo fail
fail
但要求每次使用||
/&&
也使用call
将负担放在脚本的使用者身上,而不是脚本的实现上。
这可能有用的一个例子是,如果我有一个build.cmd
脚本和一个test.cmd
脚本,我可能想运行build && test
.
https://ss64.com/nt/syntax-conditional.html https://ss64.com/nt/syntax-conditional.html and https://ss64.com/nt/exit.html https://ss64.com/nt/exit.html不要提及这种行为,即使该网站通常对批次怪异现象非常彻底。
为什么CMD会这样?有什么选择可以避免这个问题?
使用 CMD 的三个示例:
C:\> Echo @exit /b 3 > throw_err.cmd
C:\> CMD /c throw_err.cmd && echo Success || echo Error: %errorlevel%
1
C:\> CMD /K throw_err.cmd && echo Success || echo Error: %errorlevel%
C:\> exit
3
C:\> Echo @exit 3 > throw_err.cmd
C:\> CMD /c throw_err.cmd && echo Success || echo Error: %errorlevel%
3
从 PowerShell(带或不带 /b):
PS C:\> ./throw_err.cmd
PS C:\> $lastExitCode
3
当你已经在 CMD 提示符下时,必须调用一个新的 CMD 实例,只是为了获得模糊的合理错误处理,这似乎有点啰嗦,我想我更喜欢通过 PowerShell 调用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)