如何有条件地在批处理文件中编写调用命令?

时间:2011-08-05 12:59:39

标签: batch-file

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

call execute.cmd
call launch.cmd

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

execute.cmd在此处不返回任何值。

2 个答案:

答案 0 :(得分:5)

如果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命令用于评论。

HTH,
JP

答案 1 :(得分:3)

我认为这是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。

相关问题