How to capture arguments passed to a Groovy script?

Viewed 104521

I am just starting out with Groovy. I couldn't find any examples anywhere of how to handle arguments to a Groovy script and so I hacked this method myself. There must be a better way of doing this? If so, I am looking for this better way, since I am probably overlooking the obvious.

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

If you run your script with --compile-static or --type-checked option, the args variable won't be visible and therefore the compile throws an error:

[Static type checking] - The variable [args] is undeclared.

I like to do the following at the top of the script:

import groovy.transform.Field

@Field String[] args = binding.getVariable('args') as String[]

This will expose args as a global variable which can be used anywhere in the script.


References:

https://stackoverflow.com/a/53783178/2089675

https://groovy-lang.org/structure.html#_variables

Related