How to use jenkins environment variable in Jenkinsfile if statement

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.


here is some cases, hope it will save time for some people:

node {

sh 'echo "False" > output.txt'
def val = readFile 'output.txt'
echo "${val}"
echo "${val.trim()}"
if ( "${val.trim()}" ==~ /False/ ) {
    echo "Match Yes trim"
} else {
    echo "Match No trim"
}

if ( "${val}" ==~ /(?ms)False/ ) {
    echo "Match Yes (?ms)"
} else {
    echo "Match No (?ms)"
}

if ( "${val}" ==~ /(?ms)False.*/ ) {
    echo "Match Yes (?ms).*"
} else {
    echo "Match No (?ms).*"
}

if ( "${val}" =~ /False/ ) {
    echo "Match Yes 1="
} else {
    echo "Match No 1="
}

}

Output:

[Pipeline] sh
+ echo False
[Pipeline] readFile
[Pipeline] echo
False

[Pipeline] echo
False
[Pipeline] echo
Match Yes trim
[Pipeline] echo
Match No (?ms)
[Pipeline] echo
Match Yes (?ms).*
[Pipeline] echo
Match Yes 1=

Where (?ms) means multi line and s for dot matching new line in regex.

Note that echo "False" > will add newline to the file. This either needs to be trimmed or echo -n used.