2

I'm writing groovy script and trying to execute following shell command using execute() method

"mvn clean install -f \{pom directory}\pom.xml".execute()

but got an error with following message

"Cannot run program "mvn": error=2, No such file or directory"

Of course, maven is already installed and the command works well on terminal....

I also tried with "sc -c" prefix.

"sh -c mvn clean install -f \<pom directory\pom.xml".execute()

But this does execute nothing and no error at all. it seems like the command just ignored.

So how should I execute maven install in groovy script?

  • 2
    Did you try `"/complete/path/to/mvn ..."`? – SiKing Jul 18 '17 at 22:32
  • what is your operation system? windows or linux? i'm asking because you try to use sh and specifying path with backslashes. on linux path should be specified like this `/ – daggett Jul 19 '17 at 07:29
  • and finally, you would use double backslash in a string to escape the backslash from escaping the next character... Which is why forward slash is so much better in paths and works on both platforms. – Niels Bech Nielsen Jul 20 '17 at 07:09
  • did you find out how to execute this via groovyscript? – Tai Lung Jun 02 '21 at 15:27

2 Answers2

1

Since mvn is not an executable binary but a shell script, it cannot be directly executed.

This is also related to your second case where you execute sh -c .... I suspect that the environment is not properly configured. In this case the output is written to stderr which is the reason you see no output. See here on how to capture stderr.

I had this issue in a groovy script executed by Jenkins. In this situation you can for example use sh 'mvn --version' and everything is working. The sh is from the Jenkins DSL.

Michael B
  • 446
  • 1
  • 3
  • 11
0

On windows, mvn is not an exe-file but a command (mvn.cmd). I fixed the issue the following way:

def cmd = ""
if (System.properties['os.name'].toLowerCase().contains('windows')) {
    println "On Windows mvn is a CMD and not an EXE"
    cmd = "mvn.cmd wrapper:wrapper"
} else {
    println "Execute just the mvn executable on non Windows systems"
    cmd = "mvn wrapper:wrapper"
}
def process = cmd.execute(null, rootDir)
process.waitForProcessOutput((Appendable)System.out, System.err)
if (process.exitValue() != 0) {
    println "WARNING: Command '$cmd' exited with code: ${process.exitValue()}"
    println "WARNING: you can initialize the maven wrapper by yourself:}"
    println "WARNING: go to $rootDir and type in 'mvn wrapper:wrapper'}"
}