开发者

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

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 开发者_如何学Python'wc'. Any suggestions?


If you use sh -c as Aaron suggests, you can pass the whole pipeline as a single arg, effectively doing:

sh -c "ls -l foo/bar | wc -l"

If you use separate args, they are consumed by sh, not passed through to ls (hence you see just the current directory).

Note that on my system, ls -l includes a total as well as a list of the files found, which means the count shown is one more than the number of files. So suggest:

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


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.)


You need someone to recognize and build the pipe. Try sh:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜