3.11 Implementing Conditional Logic

3.11.1 Problem

You want to selectively execute portions of a build based on conditional logic.

3.11.2 Solution

Use target dependencies, properties, and the if and unless attributes of the <target> tag.

3.11.3 Discussion

Ant does not support true conditional logic, such as if/then/else. You can, however, execute targets depending on the state of properties. This target only executes if the xalanInstalled property is set:

<target name="compile" if="xalanInstalled">

If the property is not set, the target is ignored. You can also specify that a target should execute unless a property is set:

<target name="installXalan" unless="xalanInstalled">

3.11.4 See Also

Recipe 3.15 shows how to abort the build if a property is not set. This is a form of conditional logic that is specific to the fail task. See the Ant documentation for the condition task to learn how to set properties based upon existence of files, classes, or other resources.