I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy
at the top of my script.
Starting a groovy script with #!/usr/bin/env groovy
has a very important limitation - No additional arguments can be added. No classpath can be configured, no running groovy with defines or in debug. This is not a groovy issue, but a limitation in how the shebang (#!
) works - all additional arguments are treated as single argument so #!/usr/bin/env groovy -d
is telling /usr/bin/env
to run the command groovy -d
rathen then groovy
with an argument of d
.
There is a workaround for the issue, which involves bootstrapping groovy with bash in the groovy script.
#!/bin/bash
//usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@; exit $?
import org.springframework.class.from.jar
//other groovy code
println 'Hello'
All the magic happens in the first two lines. The first line tells us that this is a bash
script. bash
starts running and sees the first line. In bash
#
is for comments and //
is collapsed to /
which is the root directory. So bash
will run /usr/bin/env groovy -cp extra.jar:spring.jar:etc.jar -d -Dlog4j.configuration=file:/etc/myapp/log4j.xml "$0" $@
which starts groovy with all our desired arguments. The "$0"
is the path to our script, and $@
are the arguments. Now groovy runs and it ignores the first two lines and sees our groovy script and then exits back to bash
. bash
then exits (exit $?1
) with status code from groovy.