Nick Orton
Nick Orton

Reputation: 3663

How do I use a script's output in an Ant Conditional

I want to do something like the following

<target name="complex-conditional">
  <if>
    <exec command= "python some-python-script-that-returns-true-or-false-strings-to-stout.py/>
    <then>
      <echo message="I did sometheing" />
    </then>
    <else>
      <echo message="I did something else" />
    </else>
  </if>
</target>

How do I evaluate the result of executing some script inside of an ant conditional?

Upvotes: 5

Views: 1313

Answers (2)

xdhmoore
xdhmoore

Reputation: 9915

I created a macro to help with this:

<!-- A macro for running something with "cmd" and then setting a property
     if the output from cmd contains a given string -->
<macrodef name="check-cmd-output">
    <!-- Program to run -->
    <attribute name="cmd" />
    <!-- String to look for in program's output -->
    <attribute name="contains-string" />
    <!-- Property to set if "contains-string" is present -->
    <attribute name="property" />
    <sequential>
        <local name="temp-command-output" />
        <exec executable="cmd" outputproperty="temp-command-output">
            <arg value="/c @{cmd}" />
        </exec>
        <condition property="@{property}" >
            <contains string="${temp-command-output}" substring="@{contains-string}" />
        </condition>
    </sequential>
</macrodef>

You can then use it like so:

<target name="check-mysql-started" depends="init" >
    <check-cmd-output cmd="mysqladmin ping" contains-string="mysqld is alive" property="mysql-started" />
</target>

and then do something similar to the following:

<target name="start-mysql" depends="check-mysql-started" unless="mysql-started">
    <!-- code to start mysql -->
</target>

Admittedly, this is somewhat abusing Ant's dependency-based programming paradigm. But I've found it to be useful.

Upvotes: 1

ChssPly76
ChssPly76

Reputation: 100806

The <exec> task has outputproperty, errorproperty and resultproperty parameters that allow you to specify property names in which to store command output / errors / result code.

You can then use one (or more) of them in your conditional statement(s):

<exec command="python some-python-script-that-returns-true-or-false-strings-to-stout.py"
      outputproperty="myout" resultproperty="myresult"/>
<if>
  <equals arg1="${myresult}" arg2="1" />
  <then>
    <echo message="I did sometheing" />
  </then>
  <else>
    <echo message="I did something else" />
  </else>
</if>

Upvotes: 3

Related Questions