curl提交json数据中包含shell变量

Posted by 二田 on 2018-10-28

问题

jenkins配置中,最后build成功我会将build信息发送到钉钉中,会将一些变量发出来,这样就需要构造一些json数据

如果变量被单纯的双引号包裹的话,变量不会被解析。

curl 中引号说明如下:

The double quotes in the -H arguments (as in -H “foo bar”) tell bash to keep what’s inside as a single argument (even if it contains spaces).
The single quotes in the –data argument (as in –data ‘foo bar’) do the same, except they pass all text verbatim (including double quote characters and the dollar sign).
To insert a variable in the middle of a single quoted text, you have to end the single quote, then concatenate with the double quoted variable, and re-open the single quote to continue the text: ‘foo bar’“$variable”‘more foo’.

解决

1
curl -XPOST -H 'Content-Type: application/json' ${SERVER_URL}/report/dingding -d '{"channel": "'"${TOKEN}"'","touser":"'"${TOUSER}"'","type": "markdown","title":"'"${TITLE}"'","message": "'"${MESSAGE}"'"}'

参考

https://jaminzhang.github.io/shell/the-problem-of-curl-commit-json-data-include-shell-variables/