【问题标题】:What would be the cmd.exe alternative to bash's set -e?bash 的 set -e 的 cmd.exe 替代方案是什么?
【发布时间】:2013-07-27 14:08:09
【问题描述】:

我想获得 bash set -e 提供的相同功能,但在 Windows 批处理文件中。这怎么可能?

目前这允许我退出,但我不想在批处理文件的每一行之后添加这一行。

IF %ERRORLEVEL% NEQ 0 exit /B  %ERRORLEVEL%

【问题讨论】:

  • AFAIK 你想要的批处理文件是不可能的。
  • 难以置信的是它在cmd.exe中不存在。这就像 Java 代码到处都是空的 catch 块!

标签: batch-file cmd exit-code


【解决方案1】:

供参考

-e   errexit
      Exit immediately if a simple command exits with a non-zero
      status, unless the command that fails is part of an until or
      while loop, part of an if statement, part of a && or || list,
      or if the command's return status is being inverted using !.

http://ss64.com/bash/set.html

很遗憾,这仅靠一个命令是不可能的。

您必须在每个命令之后添加一个检查,以便在出错时退出。您可以在命令结果上使用或检查||,而不是一整行。

command || exit /b

这也可以通过将其放在开头的变量中来简化。

set "e=|| exit /b"
command1 %e%
command2 %e%

【讨论】:

    【解决方案2】:

    批处理文件的上下文很重要。这应该允许您启动多个文件并以真正的错误级别退出。

    @echo off
    for %%a in (
    "exeone"
    "exetwo"
    "exethree"
    "exefour"
    ) do "%%~a" || exit /B  %ERRORLEVEL%
    

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 2013-11-06
      • 2021-11-13
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      相关资源
      最近更新 更多