In Ant, how do I get the return value from an exec?

Use the resultproperty and failonerror attributes of the exec task, e.g.:

<target name="CheckState">
     <exec executable="${App.path}"
           resultproperty="App.state"
           failonerror="false"/>
     <echo message="App state was: ${App.state}" />
</target>

Quoting from the exec task docs Errors and return codes:

By default the return code of an exec is ignored; when you set failonerror="true" then any return code signaling failure (OS specific) causes the build to fail. Alternatively, you can set resultproperty to the name of a property and have it assigned to the result code (barring immutability, of course).

If the attempt to start the program fails with an OS dependent error code, then halts the build unless failifexecutionfails is set to false. You can use that to run a program if it exists, but otherwise do nothing.

What do those error codes mean? Well, they are OS dependent. On Windows boxes you have to look at the documentation; error code 2 means 'no such program', which usually means it is not on the path. Any time you see such an error from any Ant task, it is usually not an Ant bug, but some configuration problem on your machine.


Here is a generic way to check the result and display the output of the execution only if the process returns a failure code.

<property
    name="my.project.tmp.exec.output"
    value="${tmp.dir}/exec-output.txt"/>

<target
    name="my.project.my.task">
    <exec
        executable="${App.path}"
        output="${my.project.tmp.exec.output}"
        resultproperty="my.project.my.task.result"
        failonerror="false"/>
    <loadfile
        srcfile="${my.project.tmp.exec.output}"
        property="my.project.my.task.output"
    />
    <fail message="ERROR: ${my.project.my.task.output}">
        <condition>
            <not>
                <equals arg1="${my.project.my.task.result}" arg2="0"/>
            </not>
        </condition>
    </fail>
    <delete file="${my.project.tmp.exec.output}"/>
</target>

Tags:

Ant