【发布时间】:2011-10-20 20:44:00
【问题描述】:
我在批处理文件中有两行调用命令,如下所示:
call execute.cmd
call launch.cmd
当且仅当调用 execute.cmd 成功时,我需要调用 launch.cmd。 那么有什么方法可以在这里设置一些条件吗?
execute.cmd 在这里不返回任何值。
【问题讨论】:
标签: batch-file
我在批处理文件中有两行调用命令,如下所示:
call execute.cmd
call launch.cmd
当且仅当调用 execute.cmd 成功时,我需要调用 launch.cmd。 那么有什么方法可以在这里设置一些条件吗?
execute.cmd 在这里不返回任何值。
【问题讨论】:
标签: batch-file
我相信这是 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 -e 和 set -o pipefail 等效项。如果您愿意放弃非常有限的批处理文件语言,可以尝试 Windows PowerShell。
【讨论】:
如果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,
日本
【讨论】: