Search code examples
ant

Ant if else condition?


Is there an if/else condition that I can use for an Ant task?

This is what i have written so far:

<target name="prepare-copy" description="copy file based on condition">
        <echo>Get file based on condition</echo>
    <copy file="${some.dir}/true" todir="."  if="true"/>
</target>

The script above will copy the file if a condition is true. What if the condition is false and I wish to copy another file? Is that possible in Ant?

I could pass a param to the above task and make sure the param that's passed is


Solution

  • The if attribute does not exist for <copy>. It should be applied to the <target>.

    Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

    <target name="prepare-copy" description="copy file based on condition"
        depends="prepare-copy-true, prepare-copy-false">
    </target>
    
    <target name="prepare-copy-true" description="copy file based on condition"
        if="copy-condition">
        <echo>Get file based on condition being true</echo>
        <copy file="${some.dir}/true" todir="." />
    </target>
    
    <target name="prepare-copy-false" description="copy file based on false condition" 
        unless="copy-condition">
        <echo>Get file based on condition being false</echo>
        <copy file="${some.dir}/false" todir="." />
    </target>
    

    If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

    In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.