How to set an Ant property only if it is unset

Viewed 83646

I can't figure out how to set an Ant property on the condition that it has not been set (i.e it is not defined in the properties file and should automatically default).

So far, I only have the following code:

<condition property="core.bin" value="../bin">
    <isset property="core.bin"/>
</condition>

But this only seems to work if the value is defined in a <property> tag.

Does anyone know how to conditionally set a property for the first time if it currently unset?

5 Answers

You simply can set the property with the property-task. If the property is already set, the value is unchanged, because properties are immutable.

But you can also include 'not' in your condition:

<condition property="core.bin" value="../bin">
   <not>  
      <isset property="core.bin"/>
   </not>
</condition>

Ant does this by default; if the property is already set; setting it again has no effect:

<project name="demo" default="demo">
    <target name="demo" >
        <property name="aProperty" value="foo" />
        <property name="aProperty" value="bar" /> <!-- already defined; no effect -->
        <echo message="Property value is '${aProperty}'" /> <!-- Displays 'foo' -->
    </target>
</project>

Gives

   /c/scratch> ant -f build.xml
Buildfile: build.xml

demo:
     [echo] Property value is '${aProperty}'

BUILD SUCCESSFUL
Total time: 0 seconds
/c/scratch> ant -f build.xml
Buildfile: build.xml

demo:
     [echo] Property value is 'foo'

BUILD SUCCESSFUL

Properties cannot be redefined; to do this you need to use something like the variable task from ant-contrib.

Related