【问题标题】:How to write call command in batch file conditionally?如何有条件地在批处理文件中编写调用命令?
【发布时间】:2011-10-20 20:44:00
【问题描述】:

我在批处理文件中有两行调用命令,如下所示:

call execute.cmd
call launch.cmd

当且仅当调用 execute.cmd 成功时,我需要调用 launch.cmd。 那么有什么方法可以在这里设置一些条件吗?

execute.cmd 在这里不返回任何值。

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    我相信这是 How do I make a batch file terminate upon encountering an error? 的副本。

    您的解决方案是:

    call execute.cmd
    if %errorlevel% neq 0 exit /b %errorlevel%
    call launch.cmd
    if %errorlevel% neq 0 exit /b %errorlevel%
    

    不幸的是,Windows 批处理文件似乎没有 UNIX bash 的 set -eset -o pipefail 等效项。如果您愿意放弃非常有限的批处理文件语言,可以尝试 Windows PowerShell。

    【讨论】:

      【解决方案2】:

      如果execute.cmd 返回一个整数,则可以使用IF command 检查它的返回值,如果它与所需的值匹配,则可以调用launch.cmd

      假设execute.cmd 如果成功则返回 0,否则返回整数 >= 1。该批次将如下所示:

      rem call the execute command
      call execute.cmd
      rem check the return value (referred here as errorlevel)
      if %ERRORLEVEL% ==1 GOTO noexecute
      rem call the launch command
      call launch.cmd
      
      :noexecute
      rem since we got here, launch is no longer going to be executed
      

      请注意,rem 命令用于 cmets。

      HTH,
      日本

      【讨论】:

      • exceute.cmd 如果成功则返回 0,如果不成功则返回 1,因此使用您的逻辑解决了问题,非常感谢。正如你首先回答的那样,我接受你的回答,即使@jhclark 的回答看起来是正确的。
      • @Anand K Gupta 你好 :)
      • 您也可以通过这种方式使用 Windows Batch && 组合实现相同的目的:调用 execute.cmd && call launch.cmd
      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      相关资源
      最近更新 更多