Search code examples
bashjenkinsjenkins-pipelinejenkins-groovy

Jenkins pipeline multiline script command as variable


how can I save a command in a variable and executed anywhere in the stage

tried differnt way, but still success

here is my example

pipeline {
   agent any
   environment {
       myscript = sh '''
       echo "hello"
       echo "hello"
       echo "hello"
       '''
   }
   stages {
       stage("RUN") {
           steps {
               sh "${myscript}" 
           }          
      }
   }
}

Solution

  • you can do it like this. Not with a groovy variable but can be more dynamic with groovy function/method

    def reusableScript(message) {
        sh """
          echo Hello World
          echo Hi ${message}
        """
    }
    pipeline {
        agent any;
        stages {
            stage('01') {
                steps {
                    script {
                        reusableScript("From ${env.STAGE_NAME}")
                    }
                }
            }
            stage('02') {
                steps {
                    script {
                        reusableScript("From ${env.STAGE_NAME}")
                    }
                }
            }
        }
    }