Bash: 命令输出作为卷曲错误的变量

Bash: Command output as variable to curl error

我试图将此 bash 脚本获取到 运行 speedtest (speedtest-cli),然后通过 curl 将输出作为变量传递给 pushbullet。

#!/bin/bash
speed=$(speedtest --simple)
curl --header 'Access-Token: <-ACCESS-TOKEN->' \
     --header 'Content-Type: application/json' \
     --data-binary {"body":"'"$speed"'","title":"SpeedTest","type":"note"}' \
     --request POST \
     https://api.pushbullet.com/v2/pushes

其他命令使用此方法运行良好(例如 whoami),但 speedtestifconfig 只是得到如下错误:

{"error":{"code":"invalid_request","type":"invalid_request","message":"Failed to decode JSON body.","cat":"(=^‥^=)"},"error_code":"invalid_request"}

你的引用是错误的:

speed=$(speedtest --simple)
curl --header 'Access-Token: o.4q87SC5INy6nMQZqVHJeymwRsvMXW74j' \
     --header 'Content-Type: application/json' \
     --data-binary "{\"body\":\"$speed\",\"title\":\"SpeedTest\",\"type\":\"note\"}" \
     --request POST \
     https://api.pushbullet.com/v2/pushes

阅读此处文档可简化引用:

speed=$(speedtest --simple)
curl --header 'Access-Token: o.4q87SC5INy6nMQZqVHJeymwRsvMXW74j' \
     --header 'Content-Type: application/json' \
     --data-binary @- \
     --request POST \
     https://api.pushbullet.com/v2/pushes <<EOF
{ "body": "$speed",
  "title": "SpeedTest",
  "type": "note"
}
EOF

但是,通常您不应该假定变量的内容是正确编码的 JSON 字符串,因此请使用 jq 之类的工具为您生成 JSON .

jq -n --arg data "$(speedtest --simple)" \
   '{body: $data, title: "SpeedTest", type: "note"}' | 
 curl --header 'Access-Token: o.4q87SC5INy6nMQZqVHJeymwRsvMXW74j' \
      --header 'Content-Type: application/json' \
      --data-binary @- \
      --request POST \
      https://api.pushbullet.com/v2/pushes

这很容易重构:

post_data () {
  url=
  token=
  data=

  jq -n --arg d "$data" \
   '{body: $d, title: "SpeedTest", type: "note"}' | 
   curl --header "Access-Token: $token" \
        --header 'Content-Type: application/json' \
        --data-binary @- \
        --request POST \
        "$url"
}

post_data "https://api.pushbullet.com/v2/pushes" \
          "o.4q87SC5INy6nMQZqVHJeymwRsvMXW74j" \
          "$(speedtest ---simple)"