使用ant来检测os并设置属性

我想通过ostypes在一个ant任务中设置一个属性。

该属性是一个目录,在Windows中,我希望它是“C:\标志”在Unix / Linux“/ opt /标志”。

我当前的脚本只有当我运行它的默认目标,但为什么?

<target name="checksw_path" depends="if_windows, if_unix"/> <target name="checkos"> <condition property="isWindows"> <os family="windows" /> </condition> <condition property="isLinux"> <os family="unix" /> </condition> </target> <target name="if_windows" depends="checkos" if="isWindows"> <property name="sw.root" value="c:\flag" /> <echo message="${sw.root}"/> </target> <target name="if_unix" depends="checkos" if="isLinux"> <property name="sw.root" value="/opt/flag" /> <echo message="${sw.root}"/> </target> 

在我所有的ant目标中,我都添加了“depends = checksw_path”。

如果我在Windows中运行默认目标,我已经正确地“c:\标志”,但如果我运行一个非默认目标,我已经得到debugging进入if_windows,但指令“”不设置属性,仍然/select/标志。 我正在使用ant 1.7.1。

将你的条件移出<target /> ,因为你的目标可能不被调用。

  <condition property="isWindows"> <os family="windows" /> </condition> <condition property="isLinux"> <os family="unix" /> </condition> 

您需要将值设置为“true”才能使if条件起作用。 请参阅下面的代码:

 <target name="checkos"> <condition property="isWindows" value="true"> <os family="windows" /> </condition> <condition property="isLinux" value="true"> <os family="unix" /> </condition> </target> 

HTH,哈里

我使用这样的脚本,并为我工作得很好:

 <project name="dir" basedir="."> <condition property="isWindows"> <os family="windows" /> </condition> <condition property="isUnix"> <os family="unix" /> </condition> <target name="setWindowsRoot" if="isWindows"> <property name="root.dir" value="c:\tmp\" /> </target> <target name="setUnixRoot" if="isUnix"> <property name="root.dir" value="/i0/" /> </target> <target name="test" depends="setWindowsRoot, setUnixRoot"> <mkdir dir="${root.dir}" /> </target> </project> 

如果要设置基于操作系统的单一属性,可以直接设置它,而无需创build任务:

 <condition property="sw.root" value="c:\flag"> <os family="windows" /> </condition> <condition property="sw.root" value="/opt/flag"> <os family="unix" /> </condition> <property name="sw.root" value="/os/unknown/"/> 

尝试在您的java任务中设置<sysproperty key="foobar" value="fowl"/> 。 然后,在你的应用程序中,使用System.getProperty(“foobar”);

首先,您要基于操作系统(OS)将variables设置为true或false:

 <condition property="IS_WINDOWS" value="true" else="false"> <os family="windows"/> </condition> 

然后你想用variables触发你的逻辑。 为此,你可以在这里find答案:

http://boulderapps.co/running-different-ant-tasks-depending-on-the-operating-system

通过使用Ant Contrib,您可以通过减less需要声明的元素数量来添加这些条件来简化构build文件。

 <!--Tell Ant to define the Ant Contrib tasks from the jar--> <taskdef resource="net/sf/antcontrib/antcontrib.properties"> <classpath> <pathelement location="path/to/ant-contrib-0.6.jar"/> </classpath> </taskdef> <!--Do your OS specific stuff--> <target name="checkos"> <if> <os family="unix"/> <then> <!--Do your Unix stuff--> </then> <elseif> <os family="windows"/> <then> <!--Do your Windows stuff--> </then> </elseif> </if> </target> 

我用-Dsw.root = c:\ flag(对于windows)或-Dsw.root = / opt / superwaba(对于linux)解决了使用sw.root的值执行ant任务的问题。

不pipe怎样,谢谢