Search code examples
bashvariablesjenkinsjenkins-pluginsjenkins-groovy

Pass variable from one Jenkins stage to others in sh


I am creating Jenkins pipeline which is calling bash script functions with sh. Each stage is a bash function which set some variables whose values required in the next stages.

pipeline {
   agent any

   stages {
      stage('setName') {
         steps {
            sh "/home/setname.sh stackoverflow"
         }
      }
      stage('echoName') {
         steps {
            sh "/home/echoname.sh"
         }
      }
   }
}

setname.sh

#!/bin/bash

name=$1

echo "name: $name"

echoname.sh

#!/bin/bash

echo "setName: $name"

In the very simple example above, in setname.sh I setup name variable. Now I need to use that variable value ($name) in echoname.sh

In real code, I have a lot of variables, so getting each variable value in its file is not an option. Moreover, variables will set dynamically in one script based on passed arguments, so can't declare them globally.

Thanks in advance.


Solution

  • You can output the variables to same file in stage, then read back and assign to env at the beginning of each stage as following:

    stage('a') {
      steps {
        script {
           loadEnvs('env.props')
        }  
        sh """
          echo var1 = a >> env.props
        """
      }
    }
    
    stage('b') {
      steps {
        script {
          loadEnvs('env.props')
        }
        sh """
          echo $env.var1
    
          echo var2 = b >> env.props
        """
      }
    }
    
    def loadEnvs(propFile) {
      props = readProperties(propFile)
      props.each { key, val ->
        env[key] = val
      }
    }