Very simple and straightforward question:
Let's say we have this pipeline (I don't think there is a simpler example):
node {
env.someEnvVariable = false
boolean asBoolean = env.someEnvVariable ?: false
def asDef = env.someEnvVariable ?: false
echo "asBoolean: $asBoolean" // prints true because of Jenkins
echo "asDef: $asDef" // prints false
}
Why????
Defining a variable as boolean
makes Jenkins assign it a true value but defining it as def
assign it the real false value
Where is taking Jenkins that true
value from?
edit: another example:
node {
env.someEnvVariable = false
boolean someBoolean = false
def someVar = false
echo "envVar: ${env.someEnvVariable}" // prints false
echo "someBoolean: ${someBoolean}" // prints false
echo "someVar: ${someVar}" // prints false
if (env.someEnvVariable != null) {
someBoolean = env.someEnvVariable
someVar = env.someEnvVariable
}
echo "envVar: ${env.someEnvVariable}" // prints false
echo "someBoolean: ${someBoolean}" // prints true because of hack
echo "someVar: ${someVar}" // prints false
}
To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0.
You can use the bool method to cast a variable into Boolean datatype. In the following example, we have cast an integer into boolean type. You can also use the bool method with expressions made up of comparison operators. The method will determine if the expression evaluates to True or False.
Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.
Once you've created the build job, Jenkins will display the item's configuration page. On this configuration page, there is an unselected checkbox next to text that states: "This project is parameterized." Select this option, and in the drop-down that subsequently appears, choose the option to add a Boolean parameter.
My assumption is that when you assign environment variable it is interpreted as string 'false'
. That means in both cases you try to assign a string but assigning string to boolean
variable is interpreted as true if it is not empty.
And ternary operator works the same way, you check if environment variable is true (not empty). It's not so it returns the variable itself.
This is due to "groovy truth": a non-empty string asserts as true
.
https://docs.groovy-lang.org/latest/html/documentation/core-semantics.html#Groovy-Truth
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With