RajSanpui
RajSanpui

Reputation: 12054

Jenkins scripted pipeline: Unable to print variables inside shell and set variable values in shell

Jenkins scripted pipeline. Two issues:

  1. I have a global variable var whose value i am trying to access inside shell. But it prints nothing
  2. The value of var i am setting in one of the stages using a shell-script, to access in next stage but it prints nothing in shell.

What am i missing? (See script below)

node {    
    var=10
    stage('HelloWorld') {
        sh '''
              echo "Hello World. Var=$var"  ===> Prints nothing for var
              var=20'''

    }
    stage('git clone') {
        echo "Cloning git. Var = $var"  ==> Prints 20, and not 10
        sh '''
          echo "Var in second stage is = $var"   ===> Doesnt print anything here. I need 20.
        '''
    }
}

Upvotes: 3

Views: 10442

Answers (2)

zett42
zett42

Reputation: 27756

1. Pass a groovy variable to shell

Your sample doesn't work because you are using a string literal with single quotation marks. From Groovy manual (emphasis mine):

Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings.

Try this:

sh "echo 'Hello World. Var=$var'"

Or this:

sh """
    echo 'Hello World. Var=$var'
    echo 'More stuff'
"""        

2. Set a Groovy variable from shell

You can't directly set a Groovy variable from a shell step. This only works in one direction from Groovy to shell. Instead you can set an exit code or write data to stdout which Groovy can read.

Return a single integer

Pass true for parameter returnStatus and set an exit code from the shell script which will be the return value of the sh step.

var = sh script: 'exit 42', returnStatus: true
echo "$var"   // prints 42

Return a single string

Pass true for parameter returnStdout and use echo from shell script to output string data.

var = sh script: "echo 'the answer is 42'", returnStdout: true
echo "$var"   // prints "the answer is 42"  

Return structured data

Pass true for parameter returnStdout and use echo from shell script to output string data in JSON format.

Parse JSON data in Groovy code using JsonSlurper. Now you have a regular Groovy object that you can query.

def jsonStr = sh returnStdout: true, script: """
    echo '{
        "answer": 42,
        "question": "what is 6 times 7"
    }'
"""

def jsonData = new groovy.json.JsonSlurper().parseText( jsonStr ) 
echo "answer: $jsonData.answer"
echo "question: $jsonData.question"

Upvotes: 4

vinWin
vinWin

Reputation: 603

With withEnv we can define & then access global var.s and at stage level if you are using declarative pipeline. For scripted one we can use temp file to access between stages as per below yielding desired output.

node {    
    withEnv(['var=10']){
    stage('HelloWorld') {
        sh '''
              echo "Hello World. Var=$var" # This will print 10 from Global scope declared & defined with withEnv
              var=20
              # Hold that value in a file
              echo 20 > ${WORKSPACE}/some.file 
        '''

    }
    stage('git clone') {
        echo "Cloning git. Var = $var"  // This will print 10 as well!
        sh '''
          v=$(<${WORKSPACE}/some.file)
          echo "Var in second stage is = $v"   # Get variable value from prior stage
          rm -f ${WORKSPACE}/some.file
        '''
    }

    }
}

Upvotes: 2

Related Questions