-1

This answer did not help me

Below is the method in groovy:

def analyze(repoName){

        result= sh (
                    script: '''
                            cd ${WORKSPACE}/${BUILD_NUMBER}
                            cat > sonar-project.properties << EOF_$$
sonar.projectKey=ABC-$repoName
sonar.projectName=ABC
sonar.projectBaseDir=${WORKSPACE}/${BUILD_NUMBER}
EOF_$$
                            ''',
                    returnStatus: true
                    ) == 0
        print "Creating file - Return status: ${result}"
  }

where below line gives error:

sonar.projectKey=ABC-$repoName

properties file gets created with entry sonar.projectKey=ABC-


How to use groovy variable in sh() step?

overexchange
  • 15,768
  • 30
  • 152
  • 347

2 Answers2

2

You should use double quotes for string interpolation, so just replace '''with """

And change EOF_$$ to EOF_\$\$

khoroshevj
  • 1,077
  • 9
  • 15
  • I see errors for lines `cd ${WORKSPACE}` and `cat > sonar-project.properties << EOF_$$` after replacing `'''` with `"""`. Illegal string body – overexchange Apr 10 '19 at 19:28
  • 2
    @overexchange, check out the documentation of string usage in groovy: http://docs.groovy-lang.org/latest/html/documentation/#all-strings. `$` is a special char in double strings. You take advantage of that in variable interpolation so it needs to be escaped otherwise. – Oliver Gondža Apr 10 '19 at 19:36
  • @OliverGondža is right, you have to escape $ sign too – khoroshevj Apr 10 '19 at 19:40
  • I also need to `cd \${WORKSPACE}/\${BUILD_NUMBER}`, which I do not understand.. why? – overexchange Apr 10 '19 at 19:44
  • Do you? Because it worked for me without escaping `$` in this line, can you show the full script you are trying to execute? – khoroshevj Apr 10 '19 at 19:57
2

You should double quotes for string interpolation and escape $ by \$ in following places:

  • ${WORKSPACE} and ${BUILD_NUMBER}, you intent to use them as bash environment variable, rather than groovy variable
  • EOF_$$, you intent to use it literal meaning

Changed code:

def analyze(repoName){

        result= sh (
                    script: """
                            cd \${WORKSPACE}/\${BUILD_NUMBER}
                            cat > sonar-project.properties << EOF_\$\$
sonar.projectKey=ABC-$repoName
sonar.projectName=ABC
sonar.projectBaseDir=\${WORKSPACE}/\${BUILD_NUMBER}
EOF_\$\$
                            """,
                    returnStatus: true
                    ) == 0
        print "Creating file - Return status: ${result}"
  }
yong
  • 13,357
  • 1
  • 16
  • 27
  • So that means, before above script goes to shell, $ will interpolate and \$ will not interpolate. Is the idea? – overexchange Apr 11 '19 at 11:48
  • Yes, your understanding is correct. For more detail about string in Groovy, please read http://groovy-lang.org/syntax.html#all-strings – yong Apr 11 '19 at 14:04