Sometimes you may need to take different actions during your Java application build process, depending on if an environment variable is set. A scenario that I came across is that if a particular environment variable was set, then files needed to be copied from one location, otherwise from another.

Apache Ant is not meant to be a programming language so it is often difficult to accomplish tasks like this. However, I found a way to do this by creating two sub-targets for each boolean value of a conditional. Each target is conditionally executed by using if and unless attributes which check the property if the environment variable VARIABLE was set.

<property environment="env"/>

<condition property="exists.envVar">
    <isset property="env.VARIABLE"/>
</condition>

<target name="task" depends="-task-true, -task-false"/>

<target name="-task-true" if="exists.envVar">
    <echo>Execute something here</echo>
</target>

<target name="-task-false" unless="exists.envVar">
    <echo>Or execute this instead</echo>
</target>

The sub-targets are prepended with the - character and are also missing documentation attribute. Both of these things makes it so that they cannot be executed from the command line, and encourages the use of the top-level task target. The user calls the main target (task in this example), and the logic does the rest.