How to use a variable in a CURL request with bash?

我只是一个虾纸丫 提交于 2019-12-07 05:28:16

问题


Goal:

I'm using a bash CURL script to connect to the Cloudflare APIv4. The goal is to update an A-record. My script:

   # 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"}'

Problem:

The current_ip variable is not printed when I call it in my script. The output will be "content" : "" and not "content" : "1.2.3.4".

I used other stackoverflow posts and I'm trying to follow their examples but I think I'm still doing something wrong, just can't figure out what. :(


回答1:


Using jq for this, as Charles Duffy's answer suggests, is a very good idea. However, if you can't or do not want to install jq here is what you can do with plain 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



回答2:


The reliable way to edit JSON from shell scripts is to use 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"


来源:https://stackoverflow.com/questions/37489695/how-to-use-a-variable-in-a-curl-request-with-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!