Take the 2-minute tour ×

We want to loop through directory structure in ant without using foreach . Is there any elegant way to do the same ?

share|improve this question
What are you trying to do with the directory structure? If you're doing something like building an ant project in each directory, you may be able to get the functionality you want with subant –  David Mar 6 '13 at 16:17
add comment

2 Answers

The apply task can iterate over a set of directories or files

<target name="run-apply">
    <apply executable="echo">
        <dirset dir="src"/>

I personally like the groovy ANT task

<target name="run-groovy">
    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
    <dirset id="dirs" dir="src"/>
        project.references.dirs.each {
            ant.echo it

The installation of the task jar is easily automated:

<target name="install-groovy">
  <mkdir dir="${user.home}/.ant/lib"/>
  <get dest="${user.home}/.ant/lib/groovy-all.jar" src="http://search.maven.org/remotecontent?filepath=org/codehaus/groovy/groovy-all/2.1.1/groovy-all-2.1.1.jar"/>

Finally if you're iterating thru other build files, the subant task is very useful:

<target name="run-subant">
        <fileset dir="src" includes="**/build.xml"/>
share|improve this answer
add comment

Short answer: Not really. There are ways around this, but I prefer the ant-contrib <for/> task for clarity and simplicity. With the <local/> task, you can now localize values of variables. Before, you sometimes had to use ant-contrib's <var/> task to reset the values, so you could loop through them over and over.

<for param="directory">
    <fileset dir="${some.dir}"/>
        <local name="foo"/>
        <local name="bar"/>  <!-- Properties that may change with each iteration -->
        <!-- Here be dragons -->

It's clean, simple, and easy to understand. The big issue many people have with Ant Contrib is that not everyone may have it installed in their $ANT_HOME/lib directory. Far enough. So, if you use ant-contrib, put it as part of your project.

I'll put the ant-contrib jar in ${basedir}/antlib/antcontrib and then put this in my program:

        <fileset dir="${basedir}/antlib/antcontrib"/>

Now, when someone checks out my project, they have ant-contrib already installed (since it's inside my project) and accessible (since I point my <taskdef> task at the location of ant-contrib.jar in my project).

share|improve this answer
add comment

Your Answer


