26

How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?

The variable was put by ScriptEngine's put method

Spaceghost
  • 6,835
  • 3
  • 28
  • 42
ycomp
  • 8,316
  • 19
  • 57
  • 95

4 Answers4

42

In a groovy.lang.Script there is a method public Binding getBinding(). And groovy.lang.Binding has method public boolean hasVariable(String name).

Thus you can simply check variable existence like:

if (binding.hasVariable('superVariable')) {
// your code here
}
8
// Example usage: defaultIfInexistent({myVar}, "default")
def defaultIfInexistent(varNameExpr, defaultValue) {
    try {
        varNameExpr()
    } catch (exc) {
        defaultValue
    }
}
Maximilian Mordig
  • 1,333
  • 1
  • 12
  • 16
6

Variables injected by the Scripting Engine are held within binding.variables, so you can e.g. check for variable named xx:

if (binding.variables["xx"]) ...
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • In my context (Jenkins) I got the error : org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.Binding getVariables. The other answer didn't work either, but it wasn't a security problem. – andrew lorien Nov 14 '18 at 02:56
  • 1
    This is rather a Jenkins issue. Maybe you should ask a new question and mark it with *Jenkins* tag. – Valdi_Bo Nov 14 '18 at 08:40
  • 2
    @andrewlorien If you had catched such an error, you can go to Jenkins settings, "In-process Script Approval" and approve this script. – Michael A. Jan 01 '19 at 14:41
1

Improvement for the existing solution given here https://stackoverflow.com/a/56306660/3158217 -

def defaultIfInexistent(varName, defaultValue){
    try{
        varName.toString()
        return varName
    }catch(ex){
        return defaultValue
    }
}
Sumeet Patil
  • 422
  • 3
  • 14