【发布时间】:2020-05-24 04:52:21
【问题描述】:
如何在 Bash 脚本中将变量传递给 Curl
我无法让这个 curl 在使用环境变量的 bash 脚本中工作。 API 密钥在通过变量传入时会以某种方式被误解,并且我在提交时遇到身份验证错误。如果我将没有引号的 API 密钥作为纯文本插入,则效果很好。我尝试了各种形式的转义引号和其他组合。任何帮助都会很棒。
代码
#!/bin/bash
source .env
curl -X POST https://api.easypost.com/v2/shipments \
-u "$EASYPOST_TEST_API_KEY": \
-d 'shipment[to_address][name]=Dr. Steve Brule' \
-d 'shipment[to_address][street1]=179 N Harbor Dr' \
-d 'shipment[to_address][city]=Redondo Beach' \
-d 'shipment[to_address][state]=CA' \
-d 'shipment[to_address][zip]=90277' \
-d 'shipment[to_address][country]=US' \
-d 'shipment[to_address][phone]=8573875756' \
-d 'shipment[to_address][email]=dr_steve_brule@gmail.com' \
-d 'shipment[from_address][name]=EasyPost' \
-d 'shipment[from_address][street1]=417 Montgomery Street' \
-d 'shipment[from_address][street2]=5th Floor' \
-d 'shipment[from_address][city]=San Francisco' \
-d 'shipment[from_address][state]=CA' \
-d 'shipment[from_address][zip]=94104' \
-d 'shipment[from_address][country]=US' \
-d 'shipment[from_address][phone]=4153334445' \
-d 'shipment[from_address][email]=support@easypost.com' \
-d 'shipment[parcel][length]=20.2' \
-d 'shipment[parcel][width]=10.9' \
-d 'shipment[parcel][height]=5' \
-d 'shipment[parcel][weight]=65.9' \
【问题讨论】:
-
我唯一看到错误的是命令最后一行的
\。为什么在你的 api 密钥后面加上:?要调试,请在 curl 命令的 from 中添加echo以将其打印出来,就像脚本构建它一样。或者将-x添加到您的 bash 第一行。钥匙本身是什么?里面有什么特殊字符吗? -
这是文档所要求的,没有它,curl 会要求用户“MY_API_KEY_HERE”的主机密码。回显 curl 命令确实会在其中显示 api 密钥,因为它应该是......实际上运行它虽然会给出 API 密钥错误。
-
@JustinHammond
echo可以隐藏空格和非打印字符等内容。将-x添加到shebang(或将set -x放在curl命令之前)将更可靠地显示奇怪。 -
如果不查看所有相关内容,很难说出可能导致这种情况的原因。我建议尝试创建问题的minimal reproducible example。基本上,这意味着复制所有涉及的脚本等,然后尝试删除/简化不属于问题本身的所有内容(例如,将
curl命令替换为echo "$EASYPOST_TEST_API_KEY":,内联sourced文件等)一点一点。如果您删除某些东西并且问题消失了,请将其放回原处,因为它是问题的一部分。 -
将有问题的脚本精简到最低限度,问题通常很明显;如果不是,请将最小脚本添加到您的问题中,以便其他人可以尝试解决。