Wednesday, April 21, 2010

Ant task to check for OS before executing a batch (.bat) or shell (.sh) script

Suppose we have two scripts - one (.bat file) executes on windows os family, and other (.sh) thats runs on all non-windows platforms like unix, linux, etc. And, we need an ant task in build file, to call the appropriate scripts depending on the operating system.

Lets call this ant task "run.script", and this depends on whether OS family is windows or not windows.

<target depends="ifWindows, ifNotWindows" name="run.script"/>


This is no brainer - we are just saying that "run.script" task depends on tasks called "ifWindows" and "ifNotWindows". We then define these two tasks as below: 
   
<target name="ifWindows" if="is-windows">
   <antcall target="run.script.windows"/>
</target>


<target name="<b">"ifNotWindows" if="is-unix">
   <antcall target="run.script.unix"/>
</target>


As we see, ifWindows and ifNotWindows task are based on a condition, which if true calls the specific target.

If "is-windows" property, defind as -

<condition property=""is-windows">
    <os family="windows"/>
</condition>


returns true, than ant target "run.script.windows" is executed.

Else, ifNotWindows tested using "is-unix" property:

<condition property="is-unix">
    <not>
       <os family="windows"/>
   </not>
</condition>


If this condition returns true, then "run.script.unix" will be called.

Following is how you can define an ant task to execute a batch script on windows:

To execute a script , exec command is used wrapped inside you target definition:

<target name="run.script.windows">
    <exec dir="." executable="cmd" os="Windows Vista">
      <arg line="/c myScript.bat -p myScriptArg1 myScriptArg2"/>
   </exec>
</target>


Following is to run a shell script on unix using Ant task:

<target name=""run.script.unix">
    <exec dir="." executable="/bin/sh">
        <arg line="-c "myScript.bat -p myScriptArg1 myScriptArg2"">
</exec>
</target>



Note:
1. Note: The double-quotes are nested inside the single-quotes.
2. Using "arg line" we are passing the command and command-line parameters to be executed by the shell in one line itself. Alternatively, you may consider using "arg value" instead.

To sum up:
On systems running a Unix-type shell (for example, Cygwin on Windows) execute the (command) shell :
1. sh for shell scripts. Use -c switch to pass the shell script (.sh), any arguments to the script (as needed).
2. cmd for batch files. Use /c switch to pass the batch script (.bat), any arguments to the script (as needed).

No comments:

Post a Comment

Was this information useful?