How do I use the Ant exec task to run piped commands?

Viewed 17472

I'm trying to run the following command using the 'exec' task in Ant:

ls -l /foo/bar | wc -l

Currently, I have my exec looking like this:

<exec executable="ls" outputproperty="noOfFiles">
    <arg value="-l" />
    <arg value="/foo/bar" />
    <arg value="|" />
    <arg value="wc" />
    <arg value="-l" />
</exec>

The 'ls' command looks to be working but it's having a hard time piping the output to 'wc'. Any suggestions?

3 Answers

If you just want to count the files in a directory, don't use an external shell at all. Use the resourcecount task. Fast, compact, portable, and easy to read:

<resourcecount property="numfiles">
  <fileset dir="."/>
</resourcecount>

And you can of course customize the fileset to just include the specific files you need.

(There are actually very few cases where you need to spawn an external shell. Ant's built in I/O redirectors and input/output filter chains can often accomplish the same thing in a portable manner, even if it is sometimes a little verbose.)

Related