如何在带有 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屋!