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)

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

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:")


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

should do what you wanted.


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
}