Apache Ant – Iteration within a specific number range

Previously i have published a post about using for loop in Ant to read a text file line by line.

 

The <for> task requires a list attribute containing a comma separated string. Here is an example.

<echo message="The first five letters of the alphabet are:"/>
<for list="a,b,c,d,e" param="letter">
  <sequential>
    <echo>Letter @{letter}</echo>
  </sequential>
</for>

 

But how about if we want to iterate with a specific range? I did it by using Javascript in Ant.

<project name="AntLoopExample" default="run" basedir=".">

  <!-- Load the ant contrib lib -->
  <taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
      <pathelement location="${basedir}/ant-lib/ant-contrib-1.0b3.jar"/>
    </classpath>
  </taskdef>

  <target name="run">
    <property name="loop.start" value="4"/>
    <property name="loop.end" value="7"/>
    <script language="javascript">
      <![CDATA[
        var start = AntLoopExample.getProperty("loop.start");
        var end   = AntLoopExample.getProperty("loop.end");
        var list = start;
        for (i = parseInt(start)+1; i <= end; i++) {
          // Construct the list
          list += "," + i.toString();
        }
        AntLoopExample.setProperty("loop.list", list);
      ]]>
    </script>
    
    <!-- Iterate the list -->
    <for list="${loop.list}" param="letter">
      <sequential>
        <echo>Letter @{letter}</echo>
      </sequential>
    </for>
  </target>
</project>

 

Check it out.
ant-loop-example-2
 

Done =)

Reference:

Advertisement

2 thoughts on “Apache Ant – Iteration within a specific number range”

    1. You can even run ruby and groovy too.

      <property name="message" value="Hello world"/>
      
      <script language="groovy">
        println("message is " + message)
      </script>
      
      <script language="beanshell">
        System.out.println("message is " + message);
      </script>
      
      <script language="judoscript">
        println 'message is ', message
      </script>
      
      <script language="ruby">
        print 'message is ', $message, "\n"
      </script>
      
      <script language="jython">
        print "message is %s" % message
      </script>
      

      But i haven’t tried others~ XD

      Reference: Ant – Scriptdef

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.