Trifork Blog

Shebang! Birth of a Groovy script

May 12th, 2009 by

For a few days I have been browsing through Groovy in Action and wanted to give Groovy a try. So what should I code? I was busy with other stuff and while I was setting up a wicket project at home I wondered….what was the mvn wicket-quickstart syntax again?! I could have just pasted the command from the wicket site, but I decided to let Groovy handle this one. My first Groovy script was born. Nothing fancy, the script reads an artifactId and groupId from standard input and prods maven to create a quickstart project. It’s really nothing but a thin wrapper around the maven command. Anyway, it’s a nice opportunity to play with Groovy. Read the script below and I’ll comment right after:

#!/usr/bin/env groovy { reader ->
println "[Wicket Quickstart Script]"
print "groupId: "
def groupId = reader.readLine()
print "artifactId: "
def artifactId = reader.readLine()

def command = """/usr/bin/mvn archetype:create
-DgroupId=${groupId} -DartifactId=${artifactId}"""

def proc = command.execute() {
line -> println line

One thing I didn’t know earlier is that you can’t shebang a Groovy script as usual on a *NIX machine. Instead you put #!/usr/bin/env groovy at the top which fires up Groovy indirectly. Now the actual script. Reading the input uses a closure, similar to anonymous inner classes in Java, but way more powerful. Next, the script creates the maven command string. This part uses multi line strings, created with “”” and GStrings, which allow $variable interpolation. See Strings and GStrings. Quite useful. The final part does process management with execute(), again using a closure to loop through the maven output and print each line.

It seems that Groovy makes these scripting tasks easy to do, with very little code. From what I’ve seen so far Groovy has the familiar OO foundation of Java and the shortcut power features of scripting languages like perl and ruby. I’ll definitely use Groovy for similar scripts in the future and I am curious about using Groovy along with Java. This is really scratching the surface of what you can do with Groovy, there is a whole lot to explore!

4 Responses

  1. […] Shebang! Birth of a Groovy script « JTeam Blog / JTeam: Enterprise … […]

  2. May 14, 2009 at 11:44 by Andrea Del Bene

    Hi Frank! You should find interesting Gant project. Is based on Groovy and let you write your own task as Groovy object, without xml or command string.


  3. May 14, 2009 at 17:23 by Frank Scholten

    Hey Andrea, thanks for your comment. This page: seems to describe how to use Maven through Gant. I’ll check it out.

  4. March 19, 2010 at 13:37 by Minimalistic HTTP Clients with Groovy

    […] So, here is an example in two lines of Groovy code (really one line if you don’t count the shebang […]