shell 在bash中使用curl命令进行POST时出现异常

7z5jn7bk  于 2023-03-24  发布在  Shell
关注(0)|答案(2)|浏览(225)

我正在编写一个bash shell脚本,它通过curl命令调用Github的POST API来更新pull请求状态,下面是我使用的脚本

export scan_status=''
export status_description=''
if[ "$(param.status)" == "Succeeded" ]; then
      scan_status="success"
      status_description="scan successful"
elif[ "$(param.status)" == "Failed" ]; then
      scan_status="failure"
      status_description="scan failed"
else
     scan_status="pending"
     status_description="scan pending"
fi

_HTTP_STATUS=$(
            curl --silent --show-error --insecure \
                --connect-timeout 20 --retry 5 --retry-delay 0 --retry-max-time 60 \
                --header 'Accept: application/vnd.github.v3+json' \
                --header 'Content-Type: application/json' \
                --header 'User-Agent: TektonCD, the peaceful cat' \
                --header 'Authorization: token '${GITHUB_TOKEN} \
                --output ${_OUT_DATA} \
                --write-out "%{http_code}\n" \
                --data '{"state":"${scan_status}","target_url":"","description":"${status_description}","context":"Checkmarx/$(params.datasource)"}' \
                --request POST \
                --url "$PR_STATUS_URL" | head -1
        )

        echo "status:${_HTTP_STATUS}"

当我通过脚本点击这个时,我在调试它时得到422错误,我注意到数据部分中的参数scan_status,status_description被传递为“${scan_status}”和“${status_description}”而不是它们的值。
我试过不带双引号、用单引号括起来、不带花括号来传递它们,但都不管用。
有人能帮我修一下吗

r1zhe5dt

r1zhe5dt1#

使用 here doc,无需在JSON中引用任何内容:

curl --silent --show-error --insecure \
     --connect-timeout 20 --retry 5 --retry-delay 0 --retry-max-time 60 \
     --header 'Accept: application/vnd.github.v3+json' \
     --header 'Content-Type: application/json' \
     --header 'User-Agent: TektonCD, the peaceful cat' \
     --header 'Authorization: token "${GITHUB_TOKEN}" \
     --output "${_OUT_DATA}" \
     --write-out "%{http_code}\n" \
     --url "$PR_STATUS_URL"
     --data "@/dev/stdin"<<EOF
{"state":"${scan_status}","target_url":"","description":"${status_description}","context":"Checkmarx/$(params.datasource)"}
EOF

don't use UPPER case variables
了解如何在shell中正确引用,这非常重要:
“双引号”包括空格/元字符和 every 扩展的每个文本:"$var""$(command "$var")""${array[@]}""a & b"。将'single quotes'用于代码或文字$'s: 'Costs $5 US'ssh host 'echo "$HOSTNAME"'。请参见
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words
when-is-double-quoting-necessary

vatpfxk5

vatpfxk52#

更新此行

--data '{"state":"${scan_status}","target_url":"","description":"${status_description}","context":"Checkmarx/$(params.datasource)"}' \

--data "{\"state\":\"${scan_status}\",\"target_url\":\"\",\"description\":\"${status_description}\",\"context\":\"Checkmarx/$(params.datasource)\"}" \

注:

  • bash中不会解析单引号下的值。

相关问题