Jenkins为布尔变量赋值true,为def变量赋值false

时间:2018-02-09 14:20:37

标签: jenkins jenkins-pipeline

非常简单明了的问题:

假设我们有这个管道(我认为没有一个更简单的例子):

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
}

为什么????

将变量定义为boolean会使Jenkins为其指定一个真值,但将其定义为def会为其指定真正的假值

Jenkins认为true的价值来自哪里?

编辑:另一个例子:

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
}

2 个答案:

答案 0 :(得分:2)

我的假设是,当您分配环境变量时,它被解释为字符串'false'。这意味着在两种情况下,您都尝试分配字符串,但如果字符串不为空,则将字符串分配给boolean变量将被解释为true。

三元运算符以相同的方式工作,检查环境变量是否为真(非空)。它并非如此,它本身就会返回变量。

答案 1 :(得分:0)

这是由于“常规事实”:一个非空字符串断言为true

https://docs.groovy-lang.org/latest/html/documentation/core-semantics.html#Groovy-Truth

相关问题