I need to access Groovy-defined variables (e.g. var1) in a multi-line shell script in Jenkins. I need to use double-quote """ in sh. (I refer to here)
But I also need to read and change os system variable (e.g. aws_api_key) too. It needs to use single-quote ''' in sh and use \ to escape dollar $ sign. (I refer to here)
How can I use both of them? any help will be much appreciated.
e.g.
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
'''
}
}
}
The result is:
+ 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
Instead of multi-line String ('''
) use multi-line GString ("""
) to make string interpolation work, then ${var1}
will be interpolated as expected:
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
"""
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
so, in your case just use
def var1 = 'bin'
sh """
echo var1 = $var1
shell_var = 'yyy'
echo shell_var = \$shell_var
""""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With