4

I'd like to make my groovy script portable and I inserted in the first line:

#!/usr/bin/env groovy

The problem comes up when I run the script outside of its directory, it can't find libraries. I come from python world and all imports in python resolving relatively script's path. In groovy it seems I have to specify -classpath but I can't do that in the first #! line.

Any suggestions how to resolve it?

2
  • how about: #!/usr/bin/env groovy -cp my:class:path Commented May 24, 2012 at 3:20
  • I wouldn't like to hardcode my:class:path there and it's impossible to use something like #!/usr/bin/env groovy -cp dirname $0 Commented May 24, 2012 at 4:14

1 Answer 1

10

If the libraries are stored in a Maven repository that is accessible wherever you want to run it, one solution would be to use Grape to grab the libraries.

This provides several benefits:

  1. You don't have to worry about the classpath at all
  2. You don't have to distribute the libraries — just make sure Groovy is available on the client
  3. Libraries are downloaded just once, so even if you upgrade the application, you only have to redistribute the .groovy file.

A simple example:

#!/usr/bin/env groovy

@Grab(group='commons-io', module='commons-io', version='2.3')
import org.apache.commons.io.FileUtils

... use FileUtils like normal ...

There's a lot of existing libraries available on mvnrepository.com already.

Even if you have non-public libraries, it's relatively easy to put your own libraries into a local / private repository.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually it's not libraries but part of application - just application packages, classes, etc...
You could put all of that into a single Jar.
Possibly? A JAR is just a ZIP with a manifest. Otherwise, if you already have a bunch of loose files, why don't you just wrap your Groovy application in a shell script, and run that instead?
That's an option. Just it would be one extra file that runs the groovy script. As I said I came from python world and that wouldn't happen there. I was just curious how it worked in groovy.

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.