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

时间:2016-12-14 19:12:29

标签: bash api curl environment-variables pushbullet

我试图让这个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"}

1 个答案:

答案 0 :(得分:0)

你的报错是错误的:

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=$1
  token=$2
  data=$3

  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)"