bash中curl发起POST请求变量替换失败致422错误求助
解决bash脚本中curl --data参数变量未替换的问题
核心问题是单引号会阻止bash的变量展开,如果你的curl命令用单引号包裹--data的JSON内容,里面的${scan_status}和${status_description}会被当作字面量字符串传递,导致GitHub API收到无效JSON,返回422错误。
以下是两种可行的解决方法:
方法1:双引号包裹+转义JSON内部双引号
直接用双引号包裹整个JSON结构,同时对JSON里的双引号进行转义,让bash正常解析变量:
curl -X POST \ -H "Authorization: token YOUR_GITHUB_TOKEN" \ -H "Accept: application/vnd.github.v3+json" \ https://api.github.com/repos/OWNER/REPO/statuses/SHA \ --data "{\"state\":\"${scan_status}\",\"description\":\"${status_description}\",\"context\":\"ci/security-scan\"}"
方法2:先构造JSON变量再传递
把JSON内容通过here-doc存入变量,再传给curl,这种方式更易读,避免引号混乱:
# 构造JSON payload json_payload=$(cat <<EOF { "state": "${scan_status}", "description": "${status_description}", "context": "ci/security-scan" } EOF ) # 发起API请求 curl -X POST \ -H "Authorization: token YOUR_GITHUB_TOKEN" \ -H "Accept: application/vnd.github.v3+json" \ https://api.github.com/repos/OWNER/REPO/statuses/SHA \ --data "$json_payload"
调试技巧
在调用curl前,先打印JSON变量确认替换结果:
echo "$json_payload"
确保state的值是GitHub允许的有效值(pending/success/failure/error),description也符合API要求的长度限制。
内容的提问来源于stack exchange,提问作者Karthik Peddineni
相关产品推荐
相关产品推荐

