Search code examples
if-statementjenkinsjenkins-pipeline

How to write conditional step with boolean parameter in jenkins scripted pipeline job?


This condition in my script always gets evaluated as true and prints "Yes equal - running the stage"

stage('test cond'){  
    if(env.BUILD_TESTING2 == true){  
        echo "Yes equal - running the stage"
    } else {
        echo "Not equal - skipping the stage"
    }
}  

Even if I start the build by setting env.BUILD_TESTING2 = false it still enters the condition and prints "Yes equal - running the stage".

I also tried this syntax:

stage('test cond'){  
    if(env.BUILD_TESTING2){  
        echo "Yes equal - running the stage"
    } else {
        echo "Not equal - skipping the stage"
    }
}

But it also still always gets evaluated as true.

How can I write a conditional step with boolean parameter in Jenkins scripted pipeline ?


Solution

  • You need to convert this environment variable (of type string) to boolean using toBoolean() function:

    stage('test cond'){  
        if(env.BUILD_TESTING2.toBoolean()){  
            echo "Yes equal - running the stage"
        } else {
            echo "Not equal - skipping the stage"
        }
    }