我有以下代码段:
#!/bin/bash
set -x
TOKEN=$(./get_token.sh)
JSON='{"params": {"output": "extend" }, "auth": "'$TOKEN'"}'
echo $JSON
JSON=\'$JSON\'
echo $JSON
curl -s -X POST -d $(echo $JSON) http://localhost/api_jsonrpc.php --header "Content-Type:application/json" | jq -r -c '.result'
输出为:
++ ./get_token.sh
+ TOKEN=557d219bed92d51cb086af07a7f517d3
+ JSON='{"params": {"output": "extend" }, "auth": "557d219bed92d51cb086af07a7f517d3"}'
+ echo '{"params":' '{"output":' '"extend"' '},' '"auth":' '"557d219bed92d51cb086af07a7f517d3"}'
{"params": {"output": "extend" }, "auth": "557d219bed92d51cb086af07a7f517d3"}
+ JSON=''\''{"params": {"output": "extend" }, "auth": "557d219bed92d51cb086af07a7f517d3"}'\'''
+ echo ''\''{"params":' '{"output":' '"extend"' '},' '"auth":' '"557d219bed92d51cb086af07a7f517d3"}'\'''
'{"params": {"output": "extend" }, "auth": "557d219bed92d51cb086af07a7f517d3"}'
++ echo ''\''{"params":' '{"output":' '"extend"' '},' '"auth":' '"557d219bed92d51cb086af07a7f517d3"}'\'''
+ curl -s -X POST -d ''\''{"params":' '{"output":' '"extend"' '},' '"auth":' '"557d219bed92d51cb086af07a7f517d3"}'\''' http://localhost/api_jsonrpc.php --header Content-Type:application/json
{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}
以上内容看起来一团糟,但是这里的问题是变量JSON
作为参数传递时被弄乱了。当我回显它时,它看起来应该完全一样:
'{"params": {"output": "extend" }, "auth": "83377468223168515aa47864afad4621"}'
但是当传递到卷发时,它会被扭曲:
''\''{"params":' '{"output":' '"extend"' '},' '"auth":' '"83377468223168515aa47864afad4621"}'\'''
请注意所有多余的单引号,包括转义和非转义。我该如何处理这个问题?我希望curl
命令看起来像这样:
curl -s -X POST -d \
'{"params": {"output": "extend" }, "auth": "83377468223168515aa47864afad4621"}' \
http://localhost/api_jsonrpc.php --header "Content-Type:application/json"
首先通过创建一个文件,然后将该文件传递给curl
,使它正常工作,但这似乎是一个笨拙的解决方案。