6

Is it possible to call groovy script method from command line without using manual mapping args[]->method_to_call?

For example if I have groovy script 'MyGroovyScript.groovy' like:

def foo() {

}

def bar() {

}

And I want to call foo() method from command line like:

groovy MyGroovyScript.groovy foo
3
  • Instead of calling a method from groovy script You can put body of the method in script itself - it will be invoked and processed while script is run. Commented Apr 4, 2014 at 8:25
  • @Opal Yes, I know, but this is not what I want actually. Commented Apr 4, 2014 at 8:30
  • Any further details on what You exactly looking for? Commented Apr 4, 2014 at 8:58

2 Answers 2

11

The closest I believe you can get is:

def foo() {
    println "foo called"
}

def bar() {
    println "bar called"
}

def woo( a, b ) {
    println "Woo called with a=$a and b=$b"
}

static main( args ) {
    if( args ) {
        "${args.head()}"( *args.tail() )
    }
}

So then running the following commands give the following outputs:

$ groovy test.groovy foo
foo called

$ groovy test.groovy bar
bar called

$ groovy test.groovy woo tim yates
Woo called with a=tim and b=yates
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but OP stated: "without using manual mapping args[]->method_to_call"
Yeah, this is "The closest I believe you can get" :-/ It's almost automatic, and better than checking the args for foo or bar ;-)
Looks good, but still didn't get how does it work: '"${args.head()}"( *args.tail() )'. Will try to investigate by myself, anyway thank you! :)
@XZen args.head() gets the first argument, then wrapping it in "${args.head()}" makes it a string of this argument, and adding parentheses "${args.head()}"() makes it call the function of this name. Then, args.tail() returns the args list without the first element, and using the spread operator *args.tail() makes each element into an argument for the function call. So all together, if we say args is ['woo', 'tim', 'yates'] then it expands to woo( 'tim', 'yates' )... Nifty! ;-)
0

The shortest form I found meanwhile is the following:

groovy -e "new MyGroovyScript().foo()"

If you want to pass "MyGroovyScript" and "foo" as space-separated arguments, you can play with bash commands. Probably there are some nicer options, but one of them:

bash -c 'groovy -e "new $0().$1()"' MyGroovyScript foo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.