Home > Enterprise >  Use exit code in if statement in Jenkins pipeline
Use exit code in if statement in Jenkins pipeline

Time:02-05

Here's my Jenkins pipeline where I'm trying to to run a conditional statement on the basis of previous command's exit code.

pipeline{
    agent any
    stages{
        stage('Test exitcode'){
            steps{
                script{
                    EX_CODE = sh(
                            script: 'echo hello-world',
                            returnStatus: true
                        )
                    if( env.EX_CODE == 0 ){
                        echo "Code is good with $EX_CODE"
                    }else{
                        echo "Code is Bad with $EX_CODE"
                    }
                }
            }
        }
    }
}

Here's its output

Started by user Yatharth Sharma
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/devops/syntax-testing-pipeline
[Pipeline] { (hide)
[Pipeline] stage
[Pipeline] { (Test exitcode)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
  echo hello-world
hello-world
[Pipeline] echo
Code is Bad with 0
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

I was expecting this to return Code is good but this prints out Code is Bad. Can someone help me here with a why?

CodePudding user response:

You are assigning the int return of the exit code from the shell interpreter command from the sh step method to a variable EX_CODE. You then attempt to access the value from the env object member in the conditional as if it were an environment variable instead of a variable. You can either modify the variable to be an environment variable, or access the variable directly (simpler).

EX_CODE = sh(script: 'echo hello-world', returnStatus: true)
if (EX_CODE == 0) {
  echo "Code is good with ${EX_CODE}"
}
else{
  echo "Code is Bad with ${EX_CODE}"
}
  • Related