61

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

Fo.
  • 3,752
  • 7
  • 28
  • 44

2 Answers2

98

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

tim_yates
  • 167,322
  • 27
  • 342
  • 338
17

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

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

This statement works on my script.

bpedroso
  • 4,617
  • 3
  • 29
  • 34