Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set variables in a multi-line shell script within Jenkins Groovy?

Suppose I have a Groovy script in Jenkins that contains a multi-line shell script. How can I set and use a variable within that script? The normal way produces an error:

sh """
    foo='bar'
    echo $foo
"""

Caught: groovy.lang.MissingPropertyException: No such property: foo for class: groovy.lang.Binding

like image 727
Fo. Avatar asked Jan 27 '16 20:01

Fo.


People also ask

Can we use echo in Groovy?

Note that echo does not work in Groovy itself - only in Jenkins. println works in both.

What is SH in Jenkins pipeline?

On Linux, BSD, and Mac OS (Unix-like) systems, the sh step is used to execute a shell command in a Pipeline. Jenkinsfile (Declarative Pipeline) pipeline { agent any stages { stage('Build') { steps { sh 'echo "Hello World"' sh ''' echo "Multiline shell steps works too" ls -lah ''' } } } }


2 Answers

You need to change to triple single quotes ''' or escape the dollar \$

Then you'll skip the groovy templating which is what's giving you this issue

like image 111
tim_yates Avatar answered Oct 18 '22 21:10

tim_yates


I'm just putting a '\' on the end of line

sh script: """\
  foo='bar' \
  echo $foo \
""", returnStdout: true

This statement works on my script.

like image 30
bpedroso Avatar answered Oct 18 '22 21:10

bpedroso