How to use jenkins environment variable in Jenkinsfile if statement

Dalton Sweeney picture Dalton Sweeney · Mar 2, 2017 · Viewed 35.6k times · Source

I am trying to use an if statement in my Jenkinsfile for multi branch pipeline project. For the sake of this question, assume I have a text file in my current directory called 'scan.txt'. The text file is generated with a bash command

echo "False" > scan.txt

So the only content is the string "False"

I set an arbitrary environment variable in my Jenkinsfile to the contents of scan.txt like so:

script {
    env.TEXT = readFile 'scan.txt'
}

If I do

echo "${env.TEXT}" 

outside the script block then the jenkins console shows False for that step, as expected.

However, all of my attempts at checking if it is equal to "False" have failed. I have tried the following immediately after the script block:

if (env.TEXT.equals("False")) {
    //do something
}

if (env.TEXT.matches("False")) {
    //do something
}


if (env.TEXT == "False") {
    //do something
}

and none of them work. All of these conditions are boolean false. The documentation for the read file pipeline step states it returns a string of the file contents https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-readfile-code-read-file-from-workspace so I'm not sure what's going on here. Does anyone have any insights?

Thanks

Answer

Jon S picture Jon S · Mar 2, 2017

The problem is that when you do echo "False" > scan.txt echo will leave a line break at the end of the file, you can se this if you echo env.TEXT in your pipeline script.

So what you need to do is use String.trim() before checking if it equals False, trim will remove all white spaces at the beginning and end. Additionally, the best way of testing if a string contains is to use Boolean.parseBoolean(), it does all the hard work for you.

Let's try this:

node {
    sh 'echo "False" > output.txt'
    def val = readFile 'output.txt'
    echo "${val}"
    echo "${val.trim()}"
    if (val.equals("False")) { // This will print No
        echo "Yes"
    } else {
        echo "No"
    }
    if (val.trim().equals("False")) { // This will print Yes
        echo "Yes"
    } else {
        echo "No"
    }
    if (!Boolean.parseBoolean(val)) { // This will print Yes
        echo "Yes"
    } else {
        echo "No"
    }
}

And on the output we get:

Started by user jon
[Pipeline] node
Running on master in /var/lib/jenkins/workspace/pl
[Pipeline] {
[Pipeline] sh
[pl] Running shell script
+ echo False
[Pipeline] readFile
[Pipeline] echo
False

[Pipeline] echo
False
[Pipeline] echo
No
[Pipeline] echo
Yes
[Pipeline] echo
Yes
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

As you can se, we have an extra line break when we do the first echo step. Also note that Boolean.parseBoolean() handles the string without any trimming.