Wednesday, 13 August 2014

Executing Shell commands in Groovy


Groovy is a dynamic java language that runs on JVM. If you are familiar with Java that you will find it very easy to understand and code in Groovy. Will not go into much details now. You can refer to my earlier posts - 

Goal of this post is to show how easy it is to execute shell commands from Groovy. I am using Windows for demonstrating this but should be irrespective of OS you are using. All you have to do is make sure cURL is installed on your system which I will be using to demonstrate this example. You can refer to following posts on cURL

To the code....

 Put the following code in a file name GroovyTest.groovy and run it

class GroovyTest {
    public static void main(def args){
        def url = '';
        println("Output : " + executeCurlCommand(url));
    def static executeCurlCommand(URL){
        def url = "curl " + URL;
        def proc = url.execute();
        def outputStream = new StringBuffer();
        proc.waitForProcessOutput(outputStream, System.err)
        return outputStream.toString();

After running you can see the output same as executing the command on your console. If you need all outputs on standard output you can do

proc.waitForProcessOutput(System.out, System.err);

You can see the output by executing the same command in console

No comments:

Post a Comment

t> UA-39527780-1 back to top