drake
drake

Reputation: 101

how to use execute() in groovy to run any command

I usually build my project using these two commands from command line (dos)

G:\> cd c:
C:\> cd c:\my\directory\where\ant\exists
C:\my\directory\where\ant\exists> ant -Mysystem
...
.....
build successful

What If I want to do the above from groovy instead? groovy has execute() method but following does not work for me:

def cd_command = "cd c:"
def proc = cd_command.execute()
proc.waitFor()

it gives error:

Caught: java.io.IOException: Cannot run program "cd": CreateProcess error=2, The
 system cannot find the file specified
        at ant_groovy.run(ant_groovy.groovy:2)

Upvotes: 10

Views: 13525

Answers (5)

user17921290
user17921290

Reputation: 1

I got to fix the issue by running a command as below: i wanted to run git commands from git folder, so below is the code which worked for me.

println(["git","add","."].execute(null, new File("/Users/xyz/test-org/groovy-scripts/$GIT_REPOS/")).text)
        println(["git","commit","-m","updated values.yaml"].execute(null, new File("/Users/xyz/test-org/groovy-scripts/$GIT_REPOS/")).text)
        println(["git","push","--set-upstream","origin","master"].execute(null, new File("/Users/xyz/test-org/groovy-scripts/$GIT_REPOS/")).text)

Upvotes: 0

Zadig
Zadig

Reputation: 41

Thanks Noel and Binil, I had a similar problem with a build Maven.

projects = ["alpha", "beta", "gamma"]

projects.each{ project ->
    println "*********************************************"
    println "now compiling project " + project
    println "cmd /c mvn compile".execute(null, new File(project)).text
}

Upvotes: 4

Noel Evans
Noel Evans

Reputation: 8536

Or more explicitly, I think binil's solution should read

"your command".execute(null, new File("/the/dir/which/you/want/to/run/it/from"))

Upvotes: 15

Binil Thomas
Binil Thomas

Reputation: 13799

"your command".execute(null, /the/dir/which/you/want/to/run/it/from)

should do what you wanted.

Upvotes: 4

ccheneson
ccheneson

Reputation: 49410

According to this thread (the 2nd part), "cd c:".execute() tries to run a program called cd which is not a program but a built-in shell command.

The workaround would be to change directory as below (not tested):

System.setProperty("user.dir", "c:")

Upvotes: 5

Related Questions