命令失败时的ant exec任务

时间:2015-12-23 11:34:20

标签: ant

我有一些代码:

Pods.framework

所以,现在我想执行命令,当(1)失败时。

我该怎么办呢。

1 个答案:

答案 0 :(得分:3)

您可以使用返回码的值设置属性,然后在属性的值上有条件地执行另一个命令:

<project>
  <exec executable="${cmd}" resultproperty="ret1"/>
  <condition property="cmd1failed" value="true">
    <not>
      <equals arg1="0" arg2="${ret1}"/>
    </not>
  </condition>
  <exec executable="echo" xmlns:if="ant:if" if:true="${cmd1failed}">
    <arg value="${cmd} failed"/>
  </exec>
  <exec executable="echo" xmlns:unless="ant:unless" unless:true="${cmd1failed}">
    <arg value="${cmd} didn't fail"/>
  </exec>
</project>

例如

$ ant -f exec.xml -Dcmd=/bin/true
Buildfile: /tmp/exec.xml
     [exec] /bin/true didn't fail

BUILD SUCCESSFUL
Total time: 0 seconds
$ ant -f exec.xml -Dcmd=/bin/false
Buildfile: /tmp/exec.xml
     [exec] Result: 1
     [exec] /bin/false failed

BUILD SUCCESSFUL
Total time: 0 seconds

这使用Ant 1.9.1引入的if / unless属性。

如果您使用的是旧版本的Ant,则必须使用单独的目标,例如

<project default="both">
  <target name="cmd1">
    <exec executable="${cmd}" resultproperty="ret1"/>
    <condition property="cmd1failed" value="true">
      <not>
        <equals arg1="0" arg2="${ret1}"/>
      </not>
    </condition>
  </target>
  <target name="cmd1-fail" depends="cmd1" if="cmd1failed">
    <exec executable="echo">
      <arg value="${cmd} failed"/>
    </exec>
  </target>
  <target name="cmd1-pass" depends="cmd1" unless="cmd1failed">
    <exec executable="echo">
      <arg value="${cmd} didn't fail"/>
    </exec>
  </target>
  <target name="both" depends="cmd1-fail,cmd1-pass"/>
</project>