Groovy script - sh with variable

Something obvious is missing. How to pass a variable from groovy script to a shell command? This is in the context of the Jenkins file, if that matters for the syntax.

def COLOR node('nodename'){ stage ('color') { COLOR = "green" echo "color is $COLOR" sh '''COLOR=${COLOR} echo $COLOR''' } } 

I expect the shell text to print green , but I get the following:

 [Pipeline] echo color is green [Pipeline] sh [job] Running shell script + COLOR= + echo 

I need to use triple quoting on sh because of the content that will go through there as soon as I get this fix.

+7
source share
3 answers

To replace expressions in a string, you need to use double quotes instead of single quotes:

 def COLOR node('nodename'){ stage ('color') { COLOR = "green" echo "color is $COLOR" sh """COLOR=${COLOR} echo $COLOR""" } } 

If for some reason you need to use single quotes, try concatenating with + :

 sh '''COLOR=''' + COLOR + ''' echo ''' + COLOR 
+15
source

If the code here is intended to assign the value of the groovy variable ("green") to the COLOR environment variable, and echo $COLOR used to print the shell variable, $ must be escaped so that the shell can read it, for example:

 sh """COLOR=${COLOR} echo \$COLOR""" 
+2
source

COLOR = "green"

Label sh: '', script: "echo $ COLOR"

0
source

Source: https://habr.com/ru/post/1266658/


All Articles