Cortlendt
Cortlendt

Reputation: 2240

Pass command-line arguments to Groovy script

I have a simple Groovy script like this:

class Main {
    static void main(String... args) {
        args.each {
            println ${it}
        }
    }
}

I cannot figure out how to pass command line arguments to it. I'm on Windows and run the script as:

Groovy myscript.groovy "arg1" "arg2"

And it results in error:

Caught: groovy.lang.MissingMethodException: No signature of method: Main$_main_closure1.$() is applicable for argument types: (Main$_main_closure1$_closure2) values: [Main$_main_closure1$_closure2@68b32e3e] Possible solutions: is(java.lang.Object), is(java.lang.Object), any(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;) groovy.lang.MissingMethodException: No signature of method: Main$_main_closure1.$() is applicable for argument types: (Main$_main_closure1$_closure2) values: [Main$_main_closure1$_closure2@68b32e3e] Possible solutions: is(java.lang.Object), is(java.lang.Object), any(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;) at Main$_main_closure1.doCall(hash_text.groovy:10) at Main.main(hash_text.groovy:9)

Upvotes: 3

Views: 7767

Answers (2)

Matias Bjarland
Matias Bjarland

Reputation: 4482

Don't know if you had an explicit reason to do so, but you don't need an explicit class in groovy scripts. Also, there is an implicit args collection automatically injected into your script.

In other words, pasting the following contents into a test.groovy

println "ARGS:  $args"
println "CLASS: ${args.class}"

gives the following execution result:

~> groovy test.groovy foo bar
ARGS:  [foo, bar]
CLASS: class [Ljava.lang.String;

where the class printout means that the implicit args variable is of type String array.

Upvotes: 2

daggett
daggett

Reputation: 28634

you have just a syntax error. instead of

println ${it}

use

println it

or

println "${it}"

Upvotes: 4

Related Questions