Michał Machnicki
Michał Machnicki

Reputation: 2877

Setting value of the env variable with a shell script in a scripted pipeline

I have a scripted pipeline with one stage where I need to set the result of current build based on the output of a shell script. Unfortunately it looks that setting value with the shell script doesn't change the value of variable created using withEnv.

Is anyone able to pinpoint the mistake in the simplified snippet below (if there is one) or suggest some other solution?

stage('MyStage') {
    withEnv(["MY_VAR=null"]) {
        if (env.someCondition1 || env.someCondition2) {
            sh '''#!/bin/bash
            echo $MY_VAR              # null
            export MY_VAR="UNSTABLE"
            printenv | grep MY_VAR    # MY_VAR="UNSTABLE"
            '''
        }
        echo env.MY_VAR                   // null
        currentBuild.result = env.MY_VAR
        echo currentBuild.result          // FAILURE
    }
}

Upvotes: 0

Views: 930

Answers (1)

Corion
Corion

Reputation: 3925

The environment of a child process is lost when the child process exits. So your changes in the child to MY_VAR are lost once your child sh process is done.

You will need to communicate the change upwards to your parent, maybe by using

echo $MY_VAR

and capturing that output in the parent. Alternatively, write the values to a file and read them in the parent.

Upvotes: 1

Related Questions