Brian
Brian

Reputation: 13571

How to give a default value for a property that is not set or equals to to an empty string in Ant?

I have a build.xml file like this:

<project basedir="." default="test">
    <target name="test">
        <condition property="foo" value="${foo}" else="default_value">
            <and>
                <not>
                    <equals arg1="${foo}" arg2=""/>
                </not>
                <isset property="foo" />
            </and>
        </condition>
        <echo message="foo: ${foo}"/>
    </target>
</project>

How can I change my build.xml file to make the foo property equal to default_value when executing ant -Dfoo=${NONEXISTENT_VALUE} -buildfile build.xml shell script?

The -Dfoo=${NONEXISTENT_VALUE} passes a property to ant.

NONEXISTENT_VALUE is an environment variable that's not defined. I mean echo ${NON_EXIST_VALUE} returns an empty line.

ant -Dfoo=${NONEXISTENT_VALUE} -buildfile build.xml generates the following result:

test:
     [echo] foo:

BUILD SUCCESSFUL
Total time: 0 seconds

This is not something I want. I expected foo to be default_value. Because foo is set, and I think it is an empty string.

Upvotes: 0

Views: 1789

Answers (1)

CAustin
CAustin

Reputation: 4614

In Ant, properties defined in the command line will always take precedent over anything in the script, so you're always going to have a problem if you define foo when you run the command like this. I would suggest using the property task's environment attribute to set a prefix for your environment variables, then reference the relevant variables within the script. Here's an example of how this is done:

<target name="test">
    <property environment="env" />

    <condition property="foo" value="${env.USER}" else="default_value">
        <isset property="env.USER" />
    </condition>

    <condition property="bar" value="${env.NONEXISTANT}" else="default_value">
        <isset property="env.NONEXISTANT" />
    </condition>

    <echo message="foo: ${foo}"/>

    <echo message="bar: ${bar}"/>
</target>

Running the above text, you'll see that foo is set to your user name and bar is set to "default_value"

Upvotes: 1

Related Questions