如何使用bash在CURL请求中使用变量? [英] How to use a variable in a CURL request with bash?
问题描述
目标:
我正在使用bash CURL脚本连接到Cloudflare APIv4.目标是更新A记录.我的脚本:
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"}'
问题:
当我在脚本中调用current_ip变量时,不会将其打印出来.输出将是"content" : ""
而不是"content" : "1.2.3.4"
.
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"
.
我使用了其他 stackoverflow帖子我正在尝试遵循他们的示例,但我认为我仍然在做错事,只是无法弄清楚是什么. :(
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. :(
推荐答案
为此使用 jq ,正如查尔斯·达菲(Charles Duffy)的答案所暗示的,这是一个非常好的主意.但是,如果您不能或不想安装jq,则可以使用普通的POSIX shell进行操作.
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
这篇关于如何使用bash在CURL请求中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!