简体   繁体   English

如何将 bash 变量插入到 cURL 请求的 JSON 正文中?

[英]How do I insert a bash variable into the JSON body of a cURL request?

I am trying to run the following cURL command (taken from the ArgoCD documentation ).我正在尝试运行以下 cURL 命令(取自 ArgoCD 文档)。

$ curl $ARGOCD_SERVER/api/v1/session -d $'{"username":"admin","password":"password"}'

With the proper credentials entered manually, it runs fine, but I have my password stored in an environment variable ( $PASSWORD ) and with the both the ' and " quotes it does not insert the password correctly.使用手动输入的正确凭据,它运行良好,但我将密码存储在环境变量 ( $PASSWORD ) 中,并且使用'"引号,它无法正确插入密码。

$ curl $ARGOCD_SERVER/api/v1/session -d $'{"username":"admin","password":"$PASSWORD"}'

I suspect it uses the string literal $PASSWORD as the actual password, rather than the variable's content.我怀疑它使用字符串文字$PASSWORD作为实际密码,而不是变量的内容。 How would I insert this variable correctly?我将如何正确插入这个变量?

Like this:像这样:

curl $ARGOCD_SERVER/api/v1/session -d '{"username":"admin","password":"'$PASSWORD'"}'

or this:或这个:

curl $ARGOCD_SERVER/api/v1/session -d "{\"username\":\"admin\",\"password\":\"$PASSWORD\"}"

this'll probalby works too:这也可能会起作用:

curl $ARGOCD_SERVER/api/v1/session -d "{'username':'admin','password':'$PASSWORD'}"

or:或者:

printf -v data '{"username":"admin","password":"%s"}' "$PASSWORD"
curl $ARGOCD_SERVER/api/v1/session -d "$data"

You can use to create the JSON:您可以使用创建 JSON:

json=$(jq -c -n --arg username admin --arg password "$password" '$ARGS.named')

curl $ARGOCD_SERVER/api/v1/session -d "$json"

Using jq ensures that the JSON is properly formulated, no matter the contents of the variable:使用jq可确保 JSON jq正确,无论变量的内容如何:

$ password=$'with\'both"quotes'
$ declare -p password
declare -- password="with'both\"quotes"
$ jq -cn --arg username admin --arg password "$password" '$ARGS.named'
{"username":"admin","password":"with'both\"quotes"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM