How can I use ant <exec> to execute commands on linux?

35,853

Ant's <exec> task uses Java's Process mechanism to run commands, and this does not understand shell-specific syntax like pipes and redirections. If you need to use pipes then you have to run a shell explicitly by saying something like

<exec executable="/bin/sh">
  <arg value="-c" />
  <arg value="echo ptc@123 | sudo -S /app/Windchill_10.0/Apache/bin/apachectl -k stop" />
</exec>

but in this case it's not necessary, as you can run just the sudo command and use inputstring to provide its input rather than using a piped echo:

<exec executable="sudo" inputstring="ptc@123&#10;">
  <arg line="-S /app/Windchill_10.0/Apache/bin/apachectl -k stop" />
</exec>

Since sudo -S requires a newline character to terminate the password, I've added &#10; on the end of the inputstring (this is the simplest way to encode a newline character in an attribute value in XML).

Note that <arg line="..." /> is pretty simple minded when it comes to word splitting - if any of the command line arguments could contain spaces (for example if you need to refer to a file under a directory such as ${user.home}/Library/Application Support or if the value is read from an external .properties file that you don't control) then you must split the arguments up yourself using separate arg elements with value or file attributes, e.g.:

<exec executable="sudo" inputstring="ptc@123&#10;">
  <arg value="-S" />
  <arg file="${windchill.install.path}/Apache/bin/apachectl" />
  <arg value="-k" />
  <arg value="stop" />
</exec>
Share:
35,853
Admin
Author by

Admin

Updated on July 05, 2022

Comments

  • Admin
    Admin almost 2 years

    I would like to use ant to exectue a command like below:

    <exec executable="echo ptc@123 | sudo -S /app/Windchill_10.0/Apache/bin/apachectl -k stop">
    </exec>
    

    But it replies an error say

    The ' characters around the executable and arguments are not part of the command.

    The background is: I want to use ant to stop the apache server but it doesn't installed by the same user I run the command.

    Anyone could help or give me some clues?

    Thanks in advance

  • Erik
    Erik almost 10 years
    There's a technique to add Jenkins to sudoers so you don't have to persist the root password stackoverflow.com/a/6897382/389976