Skip to content

Instantly share code, notes, and snippets.

@mwallner
Last active October 11, 2024 05:47
Show Gist options
  • Save mwallner/aac677133f7da2a5bd94a78c09924a7e to your computer and use it in GitHub Desktop.
Save mwallner/aac677133f7da2a5bd94a78c09924a7e to your computer and use it in GitHub Desktop.
A Groovy Script that uses groovy.lang.Binding to pass arbitrary (named) paramters to another Groovy Script
/* groovylint-disable JavaIoPackageAccess, SystemExit, VariableTypeRequired */
if (args.length < 1) {
println 'Please provide either the script file path or the script content as a string.'
System.exit(1)
}
// Check if input is a file path or script content
def scriptInput = args[0]
def scriptFile = new File(scriptInput)
def params = [:]
args.each { arg ->
if (arg.startsWith('-') && arg.contains('=')) {
def (key, value) = arg.substring(1).split('=', 2)
// println " > '${key}' = '${value}'"
params.put(key, value)
}
}
def binding = new Binding(params)
def shell = new GroovyShell(binding)
if (scriptFile.exists()) {
// If it's a file path, read the file and evaluate
shell.evaluate(scriptFile)
} else {
// If it's a string (not a valid file path), assume it's script content
shell.evaluate(scriptInput)
}
@mwallner
Copy link
Author

use something like this:

groovy .\GroovyScriptRunner.groovy .\path_to_script.groovy -var=boo -with_spaces="something with spaces"

or with inline script content:

groovy .\GroovyScriptRunner.groovy "println huh; println with_spaces" -huh="asdf" -with_spaces="w i t h spaces"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment