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

JenkinsGroovyJenkins Workflow

Jenkins Problem Overview

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 """
    echo $foo

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

Jenkins Solutions

Solution 1 - Jenkins

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

Solution 2 - Jenkins

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

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

This statement works on my script.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFo.View Question on Stackoverflow
Solution 1 - Jenkinstim_yatesView Answer on Stackoverflow
Solution 2 - JenkinsbpedrosoView Answer on Stackoverflow