Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can groovy string interpolation be nested?

Tags:

jenkins

groovy

I'm trying to add parameter in Jenkins groovy shell script, then wonder if groovy string interpolation can be used nested way like this.

node{

    def A = 'C'
    def B = 'D'
    def CD = 'Value what I want'

    sh "echo ${${A}${B}}"
}

Then what I expected is like this;

'Value what I want'

as if I do;

sh "echo ${CD}"

But it gives some error that $ is not found among steps [...]

Is it not possible?

like image 788
kevmando Avatar asked Oct 18 '22 07:10

kevmando


2 Answers

Like this?

import groovy.text.GStringTemplateEngine

// processes a string in "GString" format against the bindings    
def postProcess(str, Map bindings) {
 new GStringTemplateEngine().createTemplate(str).make(bindings).toString()
}

node{

    def A = 'C'
    def B = 'D'

    def bindings = [
      CD: 'Value what I want'
    ]

    // so this builds the "template" echo ${CD}
    def template = "echo \${${"${A}${B}"}}"​
    // post-process to get: echo Value what I want
    def command = postProcess(template, bindings)

    sh command
}  
like image 113
Strelok Avatar answered Oct 20 '22 16:10

Strelok


In regard to the accepted answer, if you're putting values in a map anyway then you can just interpolate your [key]:

def A = 'C'
def B = 'D'
def bindings = [ CD: 'Value what I want' ]

bindings["${A}${B}"] == 'Value what I want'
like image 31
Cameron Basham Avatar answered Oct 20 '22 17:10

Cameron Basham