如果和除非在蚂蚁

jer*_*han 8 xml ant

我想澄清ANT脚本中的ifunless语句

我有以下代码:

<condition property="hasExtensions">
    <contains string="${Product_version}" substring="Extensions">
</condition>

<exec executable="${TrueCM_App}\ssremove.exe" unless="hasExtensions">
    ...
</exec>
Run Code Online (Sandbox Code Playgroud)

这是否意味着<exec>如果Product_version不包含字符串,上面会执行ssremove.exe "Extensions"

然后相反的情况如何:如果它包含字符串"Extensions"?我的代码看起来像这样:

<condition property="hasExtensions">
    <contains string="${Product_version}" substring="Extensions">
</condition>
<!-- here below it does not have the string "Extensions" -->
<exec executable="${TrueCM_App}\ssremove.exe" unless="hasExtensions">
    ...
</exec>

<!-- below is for if it has the string "Extensions" -->
<exec executable="${TrueCM_App}\ssremove.exe" if="hasExtensions">
    ...
</exec>
Run Code Online (Sandbox Code Playgroud)

Chr*_*isH 10

你有逻辑正确,但我不知道该<exec>任务接受ifunless属性.有关详细信息,请参阅文档.

您可能需要将<exec>任务包装在检查条件的目标中.例如:

<condition property="hasExtensions">
    <contains string="${Product_version}" substring="Extensions">
</condition>

<target name="ssremove" unless="hasExtensions">
    <exec executable="${TrueCM_App}\ssremove.exe">
        ...
    </exec>
</target>
Run Code Online (Sandbox Code Playgroud)

然后,如果你跑,ant ssremove我想你会得到你想要的.


Rhu*_*arb 7

"exec"既不支持也不支持ChrisH的回答是正确的.通常,您还会将条件包装在目标中,并使其成为另一个目标的依赖项:

<target name="-should-ssremove">
  <condition ...
</target>

<target name="ssremove" depends="-should-ssremove" unless="hasExtensions">
  ...
Run Code Online (Sandbox Code Playgroud)

注意用连字符(-should-ssremove)启动目标的惯用语,禁止从命令行使用它.(你不能做'ant -should-ssremove',因为ant会将它视为一个参数而不是一个目标 - 这在ant手册中有记录)

在这种情况下使用的另一个聪明的习惯用语,也来自手册,是利用旧的"已定义"含义if/unless和new(自Ant 1.8)扩展和与true/false的比较.

这会给你:

<target name="-should-ssremove" unless="hasExtensions">
  <condition ...
</target>

<target name="ssremove" depends="-should-ssremove" unless="${hasExtensions}">
  ...
Run Code Online (Sandbox Code Playgroud)

注意区别:第一个目标使用普通旧,除非,第二个目标扩展变量 hasExtensions(使用$ {},它们未在第一个目标中使用),并且仅在扩展为true时运行(这是默认值'available'会在其上设置,但您可以通过向'available'添加'value'属性来设置)

这个习惯用法的优点是你可以在外部设置hasExtensions属性,在导入这个属性的文件中(比如build.xml)或在命令行上:

 ant -DhasExtensions=true ssremove
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为如果已定义 hasExtensions,则不会运行-should-ssremove目标(其中,1.8之前是if/unless支持的唯一逻辑).因此,您的外部定义胜过-should-ssremove.另一方面,仅当属性hasExtensions的计算结果为false时,ssremove目标才会运行.并且它总是由它检查的时间定义 - 感谢对-should-ssremove的依赖.


小智 6

Ant 1.9.1开始,可以使用特殊命名空间在所有任务和嵌套元素上添加ifunless属性:

xmlns:if="ant:if"
xmlns:unless="ant:unless"
Run Code Online (Sandbox Code Playgroud)

看看是否和除非

<project name="tryit" xmlns:if="ant:if" xmlns:unless="ant:unless">
    <condition property="onmac">
        <os family="mac" />
     </condition>
     <echo if:set="onmac">running on MacOS</echo>
     <echo unless:set="onmac">not running on MacOS</echo>
</project>
Run Code Online (Sandbox Code Playgroud)

它还支持if:true/unless:true和if:blank/unless:blank.