Search code examples
jenkinsgroovyjenkins-pipeline

How come shell script in Jenkins pipeline does not see local variable?


I'm trying to run the following shell script in my Jenkins pipeline.

      sshagent(credentials: ['myBBCreds']) {
        sh(label: "Commit updated translation files",
           script: """
             DIFF=`git diff --name-only`
             if [ ! -z "$DIFF" ]; then
               echo "We have diffs: $DIFF"
               git add .
               git commit . -m "Jenkins ($environment - Zift123): Automated check-in of i18n files"            
             fi
           """,
           returnStatus: true)
      }

But I get the following error in my console

ERROR: groovy.lang.MissingPropertyException: No such property: DIFF for class: WorkflowScript

What am I missing? Thanks.


Solution

  • See String Iterpolation in the Jenkins Pipeline documentation.

    Since a Groovy triple double-quoted string is used to pass the shell script to the sh step, the string is first processed by Groovy trying to replace the $DIFF with a Pipeline variable. Since DIFF is a shell variable unavailable in the Groovy context, you get the error.

    A triple single quoted string should resolve the issue. e.g.:

    sh(label: "Commit updated translation files",
       script: '''
         DIFF=`git diff --name-only`
         if [ ! -z "$DIFF" ]; then
           echo "We have diffs: $DIFF"
           git add .
           git commit . -m "Jenkins ($environment - Zift123): Automated check-in of i18n files"            
         fi
       ''',
       returnStatus: true)
    

    There might be an issue with $environment if it is not a simple string variable that is part of env.