How to check if a property has value in Ant

Building on the other answers, this is my preferred form, as a Macro:

<!-- Macro to require a property is not blank -->
<macrodef name="prop-require">
    <attribute name="prop"/>
    <sequential>
        <fail message="Property &quot;@{prop}&quot; must be set">
            <condition>
                <not>
                    <isset property="@{prop}"/>
                </not>
           </condition>
        </fail>

        <fail message="Property &quot;@{prop}&quot; must not be empty">
            <condition>
                <equals arg1="${@{prop}}" arg2=""/>
           </condition>
        </fail>
    </sequential>
</macrodef>

To Be used as:

<target name="deploy.war" description="Do the war deployment ;)">
    <prop-require prop="target.vm" />
    <prop-require prop="target.vip" />
    <!-- ... -->

For brevity you can collapse the two fail elements into one by using an <or>, but I prefer my error messages to treat me like I cannot think for myself ;)


You can use conditions using the <fail> task:

<fail message="Property &quot;foo&quot; needs to be set to a value">
    <condition>
        <or>
            <equals arg1="${foo}" arg2=""/>
            <not>
                <isset property="foo"/>
            </not>
       </or>
   </condition>

This is equivalent to saying if (not set ${foo} or ${foo} = "") is pseudocode. You have to read the XML conditions from the inside out.

You could have used the <unless> clause on the <fail> task if you only cared whether or not the variable was set, and not whether it has an actual value.

<fail message="Property &quot;foo&quot; needs to be set"
    unless="foo"/>

However, this won't fail if the property is set, but has no value.


There's a trick that can make this simpler

 <!-- Won't change the value of `${foo}` if it's already defined -->
 <property name="foo" value=""/>
 <fail message="Property &quot;foo&quot; has no value">
     <condition>
             <equals arg1="${foo}" arg2=""/>
     </condition>
</fail>

Remember that I can't reset a property! If ${foo} already has a value, the <property> task above won't do anything. This way, I can eliminate the <isset> condition. It might be nice since you have three properties:

<property name="foo" value=""/>
<property name="bar" value=""/>
<property name="fubar" value=""/>
<fail message="You broke the build, you dufus">
    <condition>
        <or>
            <equals arg1="${foo}" arg2=""/>
            <equals arg1="${bar}" arg2=""/>
            <equals arg1="${fubar}" arg2=""/>
       </or>
    </condition>
</fail>

Tags:

Ant