Including a groovy script in another groovy

evaluate(new File("../tools/Tools.groovy"))

Put that at the top of your script. That will bring in the contents of a groovy file (just replace the file name between the double quotes with your groovy script).

I do this with a class surprisingly called "Tools.groovy".


As of Groovy 2.2 it is possible to declare a base script class with the new @BaseScript AST transform annotation.

Example:

file MainScript.groovy:

abstract class MainScript extends Script {
    def meaningOfLife = 42
}

file test.groovy:

import groovy.transform.BaseScript
@BaseScript MainScript mainScript

println "$meaningOfLife" //works as expected

Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:

File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();

I think that the best choice is to organize utility things in form of groovy classes, add them to classpath and let main script refer to them via import keyword.

Example:

scripts/DbUtils.groovy

class DbUtils{
    def save(something){...}
}

scripts/script1.groovy:

import DbUtils
def dbUtils = new DbUtils()
def something = 'foobar'
dbUtils.save(something)

running script:

cd scripts
groovy -cp . script1.groovy

The way that I do this is with GroovyShell.

GroovyShell shell = new GroovyShell()
def Util = shell.parse(new File('Util.groovy'))
def data = Util.fetchData()