首页 > 解决方案 > 如何在 Bash 脚本中将变量传递给 Curl

问题描述

如何在 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' \

标签: bashapicurl

解决方案


根据 Gordon Davisson 将其分解为最小请求的建议,它开始正确发送。然后我重建了它,就像我上面的问题一样,无论出于何种原因,它都像一个魅力。该-x标志在解决此问题方面也非常有帮助,但首先发现它本身并没有任何问题。感谢大家的回复!


推荐阅读