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

Jenkins执行sh步骤报Syntax error:"(" unexpected退出码2如何解决?

问题根源
  • 你获取的semgrep_result为JSON格式数据,自带{}、()、双引号、换行等shell敏感字符,直接插值到sh块的curl命令中时,这些字符会被shell解析为语法符号,而非普通字符串内容,最终触发Syntax error: "(" unexpected报错。
  • 现有curl的-d参数写法不规范,键值对未做统一转义处理,进一步加剧了shell解析异常。
解决方案

可根据服务端接收参数的格式选择对应修复方案:

方案1:服务端接收form表单参数

使用--data-urlencode自动对参数值做URL编码,规避特殊字符的shell解析问题:

script{
    sh ("pip install semgrep")
    semgrep_result = sh(script:"semgrep --config=p/r2c-ci src --json", 
                        returnStdout:true).trim()

    echo "semgrep_res $semgrep_result"

    sh"""
      curl -X POST \\
           --data-urlencode "result=$semgrep_result" \\
           --data-urlencode "discovery_source=SAST" \\
           --data-urlencode "reponame=v*****" \\
           'https://dev************/get_scan_data'
      """
}

方案2:服务端接收JSON格式参数

先通过Groovy构造标准JSON载荷,转义特殊字符后再传给curl:

import groovy.json.JsonOutput

script{
    sh ("pip install semgrep")
    semgrep_result = sh(script:"semgrep --config=p/r2c-ci src --json", 
                        returnStdout:true).trim()

    echo "semgrep_res $semgrep_result"
    // 构造完整JSON载荷,自动转义特殊字符
    def payload = JsonOutput.toJson([
        "result": semgrep_result,
        "discovery_source": "SAST",
        "reponame": "v*****"
    ])
    // 转义JSON中的单引号,避免shell截断
    payload = payload.replace("'", "'\\''")

    sh"""
      curl -X POST \\
           -H "Content-Type: application/json" \\
           -d '$payload' \\
           'https://dev************/get_scan_data'
      """
}
调试技巧

如果修改后仍有报错,可以先在sh块中添加echo打印最终执行的curl命令,查看插值后的命令是否存在语法异常:

sh "echo 'curl -X POST -d \"result\":\"$semgrep_result\" ...'"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:15:03