groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Cédric Champeau <>
Subject Re: Trick: using groovy script as a "shell script" on UNIX
Date Tue, 02 Jun 2015 09:30:54 GMT

I am curious why you don't directly use the shebang line?

On 06/02/2015 11:25 AM, Maarten Boekhold wrote:
> Hi all,
> I recently discovered a neat trick to create a standalone groovy 
> script on UNIX that you can run as if it was a shell/bash script. The 
> first part of the trick I got from the following StackOverflow post:
> You can "embed" a groovy script inside a bash script as follows:
>     #!/bin/bash
>     //usr/bin/env /path/to/groovy "$0" @0; exit $?
>     println "My groovy script"
> This launches a bash shell that runs the groovy interpreter /on this 
> same file/ ("$0"), because "//usr/bin/env" is just equivalent to 
> "/usr/bin/env" (eg the double leading slash is collapsed to a single 
> slash by bash). Groovy ignores the first line if it starts with a #, 
> and the second line starts with // which is a comment in groovy.
> If you need to add classpath entries or java properties or any other 
> command line options to groovy, you can insert them on that second 
> line as well of course, but that can generate quite a long and 
> unreadable line if you have a lot of entries. However you can use the 
> same "// trick" to set environment variables /before/ you launch groovy:
>     #!/bin/bash
>     //usr/bin/true && export CLASSPATH=....
>     //usr/bin/true && export OPTS="-Dmy.opt1=foo -Dmy.opt2=bar"
>     //usr/bin/true && export OPTS="$OPTS -Dmy.opt3=foobar"
>     //path/to/groovy $OPTS "$0" @0; exit $?
>     println System.env[my.opt1]
> Note that on the line starting groovy you don't even need to prefix it 
> with //usr/bin/env as long as you use a fully qualified path to the 
> groovy interpreter. If you want bash to find groovy in your PATH 
> however you do need that //usr/bin/env prefix.
> Neat eh? Maybe we can include this in the documentation somewhere?
> Maarten

Cédric Champeau
Groovy language developer

View raw message