Reputation: 23345
What is the most efficient way of checking if an environment variable has been set prior to executing the rest of an Ant script?
Let's say my Ant script requires the environment variable "FOO" to be set. I got the following to work, but I was wondering whether there was a less convulated way of achieving the same result:
<property environment="env"/>
<property name="env.FOO" value=""/>
<target name="my-target">
<condition property="foo.found">
<not>
<equals arg1="${env.FOO}" arg2=""/>
</not>
</condition>
<fail unless="foo.found" message="FOO not set."/>
<!-- do stuff here that uses the FOO environment variable -->
</target>
Upvotes: 14
Views: 22235
Reputation: 99
Here is what I came up with, using the isset property to check for a enviro variable that is only present on Unix. set.properties is the first target to kick this off.
<property environment="env" />
<target name="init" depends="set.properties" />
<!-- Do init stuff.... -->
</target>
<!-- Other target stuff..... -->
<!--
Target: set.properties
-->
<target name="set.properties"
description="Initializes Build Script, checks displays properties"
depends="cond.hostname.exist,cond.hostname.not.exist">
</target>
<!--
Target: check.cond HostName is Present
-->
<target name="cond.check">
<condition property="cond-is-true">
<isset property="env.HOSTNAME"/>
</condition>
</target>
<!--
Target: cond.hostname.exist
-->
<target name="cond.hostname.exist" depends="cond.check" if="cond-is-true">
<property name="targetboxname" value="${env.HOSTNAME}" />
</target>
<!--
Target: cond.hostname.not.exist
-->
<target name="cond.hostname.not.exist" depends="cond.check" unless="cond-is-true">
<property name="targetboxname" value="${env.COMPUTERNAME}" />
</target>
<!-- Then later on.... -->
<echo>ComputerName/HostName: ${targetboxname} </echo>
Upvotes: -1
Reputation: 36532
You can shorten it a bit by using an embedded <condition>
inside <fail>
.
<property environment="env"/>
<fail message="FOO not set.">
<condition>
<isset property="${env.FOO}"/>
</condition>
</fail>
Upvotes: 0
Reputation: 107040
Close:
<fail message="FOO not set.">
<condition>
<isset property="env.FOO"/>
</condition>
</fail>
This won't fail if $FOO was set, but is null.
Upvotes: 1
Reputation: 79723
Isn't this as simple as:
<property environment="env"/>
<fail unless="env.FOO" message="FOO not set."/>
Upvotes: 26
Reputation: 29473
and the other thing you can do (additional to David's) is use
<isset property="env.Foo"/> instead of <equals />
Upvotes: 9
Reputation: 46395
<property name="test.home.0" value="${env.TEST_HOME}"/>
<condition property="test.home" value="TO_BE_REPLACED">
<equals arg1="${test.home.0}" arg2="\${env.TEST_HOME}"/>
</condition>
<property name="test.home" value="${env.TEST_HOME}"/>
<target name="test">
<echo>TEST_HOME: ${test.home}</echo>
</target>
Upvotes: 0