【问题标题】:Bash: Command output as variable to curl errorBash:命令输出作为 curl 错误的变量
【发布时间】:2016-12-14 19:12:29
【问题描述】:

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

【问题讨论】:

    标签: bash api curl environment-variables pushbullet


    【解决方案1】:

    你的引用是错误的:

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

    【讨论】:

    • 这行得通! (在 ---simple 中有一个额外的破折号)thanx!
    • 如何将此输出与其他文本和变量结合起来,如下所示:body="Local IP: $iplocal\nPublic IP: $ippublic\nSpeedtest: \n$data"
    • 我可以将 speedtest 命令和输出定义为一个变量,以便我可以轻松地添加更多变量并测试到正文吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2020-12-19
    • 2020-03-22
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多