Skip to content

Instantly share code, notes, and snippets.

@rashkur
Forked from pradhyu/undefinedVariable.groovy
Created September 23, 2020 15:23
Show Gist options
  • Save rashkur/a5e2b56a6d0990f294cb08865176270c to your computer and use it in GitHub Desktop.
Save rashkur/a5e2b56a6d0990f294cb08865176270c to your computer and use it in GitHub Desktop.
Check if a variable is undefined in groovy
// checking bindings snippets
if (binding.hasVariable('superVariable')) {
// your code here
}
An easy solution to this is the following:
if (binding.variables.containsKey("bindingVar")) {
// do something
}
Or if you’d like to get a null value for an optional binding:
def optVar = binding.variables.get("bindingVar")
if (optVar) {
// do something
}
// Local vs global vars
def bindingVar (varName) {
def optVar = binding.variables.get(varName)
if (optVar) {
println(optVar)
//will only run for global var
}
optVar
}
def localVar="localVariable"
bindingVar("localVar")
globalVar="global variable"
bindingVar("globalVar")
/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment