Ori*_*pax 4 shell groovy jenkins
我需要在 Jenkins 的多行 shell 脚本中访问 Groovy 定义的变量(例如 var1)。我需要在sh中使用双引号"""。(我指的是here)
但我也需要读取和更改 os 系统变量(例如 aws_api_key)。它需要在 sh 中使用单引号 ''' 并使用 \ 来转义美元 $ 符号。(我指的是这里)
我怎样才能同时使用它们?任何帮助都感激不尽。
例如
node ("Jenkins-Test-Slave") {
stage ("hello world") {
echo 'Hello World'
}
def var1="bin"
stage ("test") {
withEnv(["aws_api_key='define in withEnv'","service_url=''"]) {
echo var1
sh '''
echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
echo default value of aws_api_key is \$aws_api_key
aws_api_key='changed in shell'
echo new value of aws_api_key is \$aws_api_key
export newvar='newxxx'
echo the new var value is \$newvar
'''
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果是:
+ echo the groovy data var1 is ,${var1},,,var1!!!
the groovy data var1 is ,${var1},,,var1!!!
+ echo default value of aws_api_key is 'define in withEnv'
default value of aws_api_key is 'define in withEnv'
+ aws_api_key=changed in shell
+ echo new value of aws_api_key is changed in shell
new value of aws_api_key is changed in shell
+ export newvar=newxxx
+ echo the new var value is newxxx
the new var value is newxxx
Run Code Online (Sandbox Code Playgroud)
代替 multi-line String( ''') 使用 multi-line GString( """) 使字符串插值工作,然后${var1}将按预期进行插值:
sh """
echo the groovy data var1 is "${var1}",'\${var1}',\$var1,${var1},var1!!!
echo default value of aws_api_key is \$aws_api_key
aws_api_key='changed in shell'
echo new value of aws_api_key is \$aws_api_key
export newvar='newxxx'
echo the new var value is \$newvar
"""
Run Code Online (Sandbox Code Playgroud)
def var1 = 'bin'
//the following are `groovy` strings (evaluated)
sh "echo var1 = $var1"
//outputs> echo var1 = bin
sh "echo var1 = ${var1}"
//outputs> echo var1 = bin
sh """echo var1 = ${var1}"""
//outputs> echo var1 = bin
sh "echo var1 = \$var1"
//outputs> echo var1 = $var1
//the following are usual strings (not evaluated)
sh 'echo var1 = $var1'
//outputs> echo var1 = $var1
sh '''echo var1 = $var1'''
//outputs> echo var1 = $var1
Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下只需使用
def var1 = 'bin'
sh """
echo var1 = $var1
shell_var = 'yyy'
echo shell_var = \$shell_var
""""
Run Code Online (Sandbox Code Playgroud)