首页 > 解决方案 > Groovy 比较字符串

问题描述

我有如下的 Groovy 代码

def retVal = sh(returnStdout: true, script: "curl ${URI}; echo \$?")

println("Return value: ${retVal}") -> it printed 0

if (retVal == "0") {

    println("Successfull") -> it doesn't go here

}

为什么无法捕捉到上述情况?

标签: groovy

解决方案


首先,您似乎错误地使用了 Jenkins API。

如果您只需要进程的退出代码,请使用returnStatus: true

def retVal = sh(returnStatus: true, script: "curl ${URI}")
if (retVal == 0) {
    println 'success'
} else {
    println "Something wrong, exit code was $retVal")
}

现在,如果你真的想要标准输出,也许首先通过调用它来清理字符串trim(),或者尝试将字符串与正则表达式匹配:

if (retValue ~== /\s*0\s*/) {
    println "success"
} else {
    println "Something wrong, exit code was '$retVal'")
}

我总是在我打印的值周围加上引号,以确保换行符或空格不会让我在错误的值上浪费时间。


推荐阅读