2017-08-23 56 views
1

我想在Jenkins groovy shell腳本中添加參數,然後想知道groovy字符串插值是否可以像這樣使用嵌套方式。可以groovy字符串插值嵌套?

node{ 

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

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

那麼我的預期是這樣的;

'Value what I want' 

好像我這樣做;

sh "echo ${CD}" 

但它給一些錯誤$未步驟中發現[...]

是沒可能?

回答

0

是否這樣?

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 
} 
+1

它適合你嗎?對我而言,它什麼也不打印。 – kevmando

+0

我沒有在詹金斯嘗試。但是如果你運行這個腳本https://groovyconsole.appspot.com/script/5098840017338368它會打印'echo $ {CD}'。我的猜測是OP想要的。如果不是,那麼我不明白這個問題。 – Strelok

+1

我在找的是打印CD的價值 - '我想要的價值'。 – kevmando

0

${A}${B}是不正確的groovy語法。

插值僅插入${}之間的表達式值。

即使您更改爲正確的語法並創建$方法,結果也不會是您想要的。

def nested = "${${A}+${B}}" 
    println nested 


static $(Closure closure) { //define $ method 
    closure.call() 
} 

CD將被打印。

+0

感謝。它看起來像迄今爲止,所以我發佈了一個問題,以確認是否有人可能知道。 – kevmando

0

至於接受的答案,如果你把值映射反正那麼你可以只插你的[關鍵]:

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

bindings["${A}${B}"] == 'Value what I want'