Running a script from Groovy
Solution 1
Groovy added an execute() method to plain old String, so try this:
println "ls -la".execute().text
Solution 2
The execute() method can be used to change directories if you prefix it with the "cmd /c" command, and then use ampersand (assuming Windows) to chain commands together.
Example, assuming you want to go to subdirectory subdir and run a couple of batch files from there:
println "cmd /c cd subdir & batch1.bat & batch2.bat".execute().text
Not sure if there isn't a better way, but this does work.
Solution 3
You can also use ProcessBuilder which is a surprisingly convienent Java class introduced in java 5.
ProcessBuilder lets you
- determine the working directory
- determine which environmental variables the process should have
See http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html for a brief example and more documentation.
![raoulsson](https://i.stack.imgur.com/D8nV6.jpg?s=256&g=1)
raoulsson
Before: CTO Contovista AG, Zurich, Co-founder Zorp Technologies Inc., SF, Manager and Chief System Architect at Leonteq, and many more... Experienced software engineer and teamlead looking to build/enable useful, delightful, and meaningful products. Passionate, hard-worker interested in contributing to team-oriented, strong engineering cultures. Proven track record of hiring and running successful teams.
Updated on July 01, 2022Comments
-
raoulsson almost 2 years
In order to get my setup a bit closer to "one click deployment", I would like to use groovy scripts to start/stop other processes controlled by bat scripts, running in different parts of the filesystem and even on different machines.
How to execute these scripts and how to do it from their respective working directory?
I know Java's
java.lang.Runtime's exec()
However there are lots of issues with this and I wondered if Groovy had some kind of shorthand for this as well?
Thanks!
-
FabienB over 9 yearsI second that. Here's a blog post that combines Groovy and the ProcessBuilder
-
Alexander Stohr over 3 yearsyou are a lucky one that "ls" is a stand-alone executable - and not a shell built in command.
-
Alexander Stohr over 3 yearsfor something similar on a Linux system you might need to do a variant like this: [ 'sh', '-c', 'your-commands-here'].execute().text - whilst on Windows systems command parsing of a single string is already in there under the hood (it might or might not be part of the api spec.)