You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Pipeline执行jq命令后输出无法保存到变量问题求助

问题原因

Jenkins Pipeline 的 sh 步骤默认返回值为命令的退出状态码,只有显式配置 returnStdout: true 参数时,才会将命令的标准输出内容作为返回值赋值给变量。你代码中执行jq的两次sh调用都没有加该参数,因此变量拿到的是空值(null),日志中打印的只是sh步骤默认输出的命令执行内容,并没有存入变量。

修正方案

你可以直接修改sh调用部分,补充returnStdout: true参数,同时添加.trim()方法去除输出末尾自带的换行符,避免后续使用变量时出现格式异常:

def lines = stageOneList.readLines()
lines.each { line -> println line
    // 简化curl命令的字符串拼接,避免引号嵌套错误
    stageTwoList = sh (
        script: "curl -u $apptoken -X GET --url \"${appurl}components/tree?component=${line}\"", 
        returnStdout: true
    ).trim()                                
    pfName = sh (
        script: "jq -r '.component.name' <<< '${stageTwoList}'", 
        returnStdout: true
    ).trim()
    pfKey = sh (
        script: "jq -r '.component.key' <<< '${stageTwoList}'", 
        returnStdout: true
    ).trim()
    echo "Component Names and Keys\n | $pfName | $pfKey |"
}

优化建议

如果你的Jenkins安装了「Pipeline Utility Steps」插件,完全可以不用调用shell执行jq,直接用内置的readJSON方法解析接口返回的JSON内容,性能更高且不会出现shell转义问题:

def lines = stageOneList.readLines()
lines.each { line -> println line
    stageTwoList = sh (
        script: "curl -u $apptoken -X GET --url \"${appurl}components/tree?component=${line}\"", 
        returnStdout: true
    ).trim()
    // 直接在Groovy层面解析JSON,无需调用jq
    def respData = readJSON text: stageTwoList
    def pfName = respData.component.name
    def pfKey = respData.component.key
    echo "Component Names and Keys\n | $pfName | $pfKey |"
}

内容的提问来源于stack exchange,提问作者Innocentspirit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:48:04