Friday, 15 August 2014

How to capture arguments passed to a Groovy script?

It is very much similar to Java and you can use the same java syntax. For eg.

class TestExecutor {

    public static void main(def args) {
        println("Printing arguments");
        for(String arguments : args) {
            println (arguments);
        }
    }
} 


Run it and you should see the arguments printed



Also note if you do not provide main method or provide one like in above example then you can get arguments as args[i] but you can change the name of the array (again same as java). So you can have something like -

public static void main(def argsNew) {

    println("Printing arguments");

    for(String arguments : argsNew) {

        //using args in above for loop will throw error

        println (arguments);

    }

}


Point being it's not something that is hard-coded. Finally as suggested in other answer you can always use CliBuilder for smart parsing. But again in that too it internally used def options = cli.parse(args).

Finally there is always the hard way to do things (Just putting here for code coverage and additional information - no need to use this code for fetching arguments) -

import groovy.lang.Binding;
Binding binding = new Binding();
int x = 1
for (a in this.args) {
  println("arg$x: " + a)
  binding.setProperty("arg$x", a);
  x=x+1
}
println binding.getProperty("arg1")
println binding.getProperty("arg2")
println binding.getProperty("arg3") 

Important Links

No comments:

Post a Comment

t> UA-39527780-1 back to top