0

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
    }
}
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

echo $MY_VAR doesn't communicate the change upwards. Saving the value to a file is indeed one of the possible solutions but I was hoping that jenkins is somehow communicating back the values of the shared env variables
That's what I said in the second part, and capturing that output in the parent :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.