Command line to run the Ant task with hyphen in th

2019-03-10 22:18发布

问题:

The task name starts with a hyphen "-".

<?xml version="1.0" encoding="UTF-8"?>
<project name="proj">
    <target name="-task1">
        <echo>Done!</echo>
    </target>
</project>

How can I specify this task when running ant script from command line? This would not work:

ant -task1 -f test.xml

回答1:

Enclose the task name in quotes.

ant "-task1" -f test.xml

Update: From Ant docs

Targets beginning with a hyphen such as "-restart" are valid,
and can be used to name targets that should not be called directly
from the command line.
For Ants main class every option starting with hyphen is an option for Ant itself
and not a target. For that reason calling these target from command line is not
possible. On the other hand IDEs usually don't use Ants main class as entry 
point and calling them from the IDE is usually possible.


回答2:

Some people start internal targets with dashes just to make sure users cannot run them from the command line. In fact, I make it a standard practice to have all internal targets start with - just for this reason.

You can try the old double-dash trick. I don't have Ant installed on my current system, so I can't test it. Double dashes is a common Unix trick that most commands use to help end parameters when you have files and stuff that start with a dash. By the way, the tasks should be the last thing on your command line:

$ ant -f test.xml -- -task1

Worse comes to worse, you can simply define another target in your build.xml file that depends upon this target with the dash in it:

<task name="sneaky"
    depends="-task1"/>

Then you should be able to call sneaky:

$ant -f test.xml sneaky


回答3:

From the ANT target doc

Targets beginning with a hyphen such as "-restart" are valid, and can be used to name targets that should not be called directly from the command line. For Ants main class every option starting with hyphen is an option for Ant itself and not a target. For that reason calling these target from command line is not possible.

So, user cannot call the target with hyphen from commandline.

Tested on Windows Platform on 21 April 2016.



标签: ant