我创建了一个宏来帮助这个:
<!-- 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>
然后可以使用它像这样:
<target name="check-mysql-started" depends="init" >
<check-cmd-output cmd="mysqladmin ping" contains-string="mysqld is alive" property="mysql-started" />
</target>
,然后做类似下面的内容:
<target name="start-mysql" depends="check-mysql-started" unless="mysql-started">
<!-- code to start mysql -->
</target>
诚然,这是有点滥用Ant的基于依赖的编程范式。但我发现它是有用的。