如何使用bash在CURL请求中使用变量?

时间:2016-05-27 17:57:51

标签: bash shell api curl cloudflare

目标:

我使用bash CURL脚本连接到Cloudflare APIv4。目标是更新A记录。我的剧本:

   # Get current public IP
      current_ip=curl --silent ipecho.net/plain; echo

   # Update A record
      curl -X PUT "https://api.cloudflare.com/client/v4/zones/ZONEIDHERE/dns_records/DNSRECORDHERE" \
        -H "X-Auth-Email: EMAILHERE" \
        -H "X-Auth-Key: AUTHKEYHERE" \
        -H "Content-Type: application/json" \
        --data '{"id":"ZONEIDHERE","type":"A","name":"example.com","content":"'"${current_ip}"'","zone_name":"example.com"}'

问题:

当我在脚本中调用current_ip变量时,不会打印它。输出将为"content" : ""而不是"content" : "1.2.3.4"

我使用了other stackoverflow帖子,我试图按照他们的例子,但我认为我仍然做错了什么,只是无法弄清楚是什么。 :(

2 个答案:

答案 0 :(得分:5)

正如Charles Duffy的回答所示,使用jq是一个非常好的主意。但是,如果你不能或不想在这里安装jq就可以使用普通的POSIX shell。

#!/bin/sh
set -e

current_ip="$(curl --silent --show-error --fail ipecho.net/plain)"
echo "IP: $current_ip"

# Update A record
curl -X PUT "https://api.cloudflare.com/client/v4/zones/ZONEIDHERE/dns_records/DNSRECORDHERE" \
    -H "X-Auth-Email: EMAILHERE" \
    -H "X-Auth-Key: AUTHKEYHERE" \
    -H "Content-Type: application/json" \
    --data @- <<END;
{
    "id": "ZONEIDHERE",
    "type": "A",
    "name": "example.com",
    "content": "$current_ip",
    "zone_name": "example.com"
}
END

答案 1 :(得分:3)

从shell脚本编辑JSON的可靠方法是使用jq

# set shell variables with your contents
email="yourEmail"
authKey="yourAuthKey"
zoneid="yourZoneId"
dnsrecord="yourDnsRecord"

# make sure we show errors; --silent without --show-error can mask problems.
current_ip=$(curl --fail -sS ipecho.net/plain) || exit

# optional: template w/ JSON content that won't change
json_template='{"type": "A", "name": "example.com"}'

# build JSON with content that *can* change with jq
json_data=$(jq --arg zoneid="$zoneid" \
               --arg current_ip="$current_ip" \
               '.id=$zoneid | .content=$current_ip' \
               <<<"$json_template")

# ...and submit
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records/$dnsrecord" \
  -H "X-Auth-Email: $email" \
  -H "X-Auth-Key: $authKey" \
  -H "Content-Type: application/json" \
  --data "$json_data"