Performing Batch Execution

What if you want to execute a command on multiple files? If you want to pass a set of files to an external command, use the apply task, a version of exec that takes filesets. The files in the fileset are passed as arguments to the command or external program.

This task is a powerful one, letting you batch your executions and work with external programs as if they supported filesets. In Example 7-5, the build file is running the C compiler gcc on a fileset. In this case, the apply task executes the command line gcc -c -o target source for each .c file in ${src}, where source with the name of each matching .c file in turn, and target is replaced with the name of the corresponding .o output file you want created.

Example 7-5. Using the apply task (ch07/apply/build.xml)

<?xml version="1.0" ?>
<project default="main">

    <property name="src" location="source" />

    <target name="main">
        <apply executable="gcc">
            <arg value="-c"/>
            <arg value="-o"/>
            <targetfile/>
            <srcfile/>
            <fileset dir="${src}" includes="*.c" />
            <mapper from="*.c" to="*.o" type="glob" />
        </apply>
    </target>
</project>

You can see this task's attributes Table 7-4.

Table 7-4. The apply task's attributes

Attribute

Description

Required

Default

addsourcefile

Specifies if you want source filenames to be added to the command automatically. Since Ant 1.6.

No

true

append

Specifies whether you want to append to output and error files.

No

false

dest

Specifies the directory in which files will be stored by the task. ...

Get Ant: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.