json 将 curl POST 与 bash 脚本函数中定义的变量一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17029902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using curl POST with variables defined in bash script functions
提问by AGleasonTU
When I echo I get this, which runs when I enter it into the terminal
当我回声时,我得到了这个,当我将它输入到终端时运行
curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data '{"account":{"email":"[email protected]","screenName":"akdgdtk","type":"NIKE","passwordSettings":{"password":"Starwars1","passwordConfirm":"Starwars1"}},"firstName":"Test","lastName":"User","middleName":"ObiWan","locale":"en_US","registrationSiteId":"520","receiveEmail":"false","dateOfBirth":"1984-12-25","mobileNumber":"9175555555","gender":"male","fuelActivationDate":"2010-10-22","postalCode":"10022","country":"US","city":"Beverton","state":"OR","bio":"This is a test user","jpFirstNameKana":"unsure","jpLastNameKana":"ofthis","height":"80","weight":"175","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}' https://xxx:[email protected]/xxxxx/xxxx/xxxx
But when run in the bash script file, I get this error
但是当在 bash 脚本文件中运行时,我收到此错误
curl: (6) Could not resolve host: application; nodename nor servname provided, or not known
curl: (6) Could not resolve host: is; nodename nor servname provided, or not known
curl: (6) Could not resolve host: a; nodename nor servname provided, or not known
curl: (6) Could not resolve host: test; nodename nor servname provided, or not known
curl: (3) [globbing] unmatched close brace/bracket at pos 158
this is the code in the file
这是文件中的代码
curl -i \
-H '"'Accept: application/json'"' \
-H '"'Content-Type:application/json'"' \
-X POST --data "'"'{"account":{"email":"'$email'","screenName":"'$screenName'","type":"'$theType'","passwordSettings":{"password":"'$password'","passwordConfirm":"'$password'"}},"firstName":"'$firstName'","lastName":"'$lastName'","middleName":"'$middleName'","locale":"'$locale'","registrationSiteId":"'$registrationSiteId'","receiveEmail":"'$receiveEmail'","dateOfBirth":"'$dob'","mobileNumber":"'$mobileNumber'","gender":"'$gender'","fuelActivationDate":"'$fuelActivationDate'","postalCode":"'$postalCode'","country":"'$country'","city":"'$city'","state":"'$state'","bio":"'$bio'","jpFirstNameKana":"'$jpFirstNameKana'","jpLastNameKana":"'$jpLastNameKana'","height":"'$height'","weight":"'$weight'","distanceUnit":"MILES","weightUnit":"POUNDS","heightUnit":"FT/INCHES"}'"'" "https://xxx:[email protected]/xxxxx/xxxx/xxxx"
I assume there's an issue with my quotation marks, but I've played with them a lot and I've gotten similar errors. All the variables are defined with different functions in the actual script
我认为我的引号有问题,但我已经玩过很多次了,我也遇到过类似的错误。所有变量都在实际脚本中用不同的函数定义
回答by Sir Athos
You don't need to pass the quotes enclosing the custom headers to curl. Also, your variables in the middle of the dataargument should be quoted.
您不需要将包含自定义标题的引号传递给 curl。此外,data应该引用参数中间的变量。
First, write a function that generates the post data of your script. This saves you from all sort of headaches concerning shell quoting and makes it easier to read an maintain the script than feeding the post data on curl's invocation line as in your attempt:
首先,编写一个生成脚本发布数据的函数。这使您免于与 shell 引用有关的各种头痛,并且比在尝试时在 curl 的调用行上提供 post 数据更容易阅读维护脚本:
generate_post_data()
{
cat <<EOF
{
"account": {
"email": "$email",
"screenName": "$screenName",
"type": "$theType",
"passwordSettings": {
"password": "$password",
"passwordConfirm": "$password"
}
},
"firstName": "$firstName",
"lastName": "$lastName",
"middleName": "$middleName",
"locale": "$locale",
"registrationSiteId": "$registrationSiteId",
"receiveEmail": "$receiveEmail",
"dateOfBirth": "$dob",
"mobileNumber": "$mobileNumber",
"gender": "$gender",
"fuelActivationDate": "$fuelActivationDate",
"postalCode": "$postalCode",
"country": "$country",
"city": "$city",
"state": "$state",
"bio": "$bio",
"jpFirstNameKana": "$jpFirstNameKana",
"jpLastNameKana": "$jpLastNameKana",
"height": "$height",
"weight": "$weight",
"distanceUnit": "MILES",
"weightUnit": "POUNDS",
"heightUnit": "FT/INCHES"
}
EOF
}
It is then easy to use that function in the invocation of curl:
然后很容易在调用 curl 时使用该函数:
curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data "$(generate_post_data)" "https://xxx:[email protected]/xxxxx/xxxx/xxxx"
This said, here are a few clarifications about shell quoting rules:
这就是说,这里有一些关于 shell 引用规则的说明:
The double quotes in the -Harguments (as in -H "foo bar") tell bash to keep what's inside as a single argument (even if it contains spaces).
-H参数中的双引号(如-H "foo bar")告诉 bash 将里面的内容保留为单个参数(即使它包含空格)。
The single quotes in the --dataargument (as in --data 'foo bar') do the same, except they pass all text verbatim (including double quote characters and the dollar sign).
--data参数中的单引号(如--data 'foo bar')的作用相同,除了它们逐字传递所有文本(包括双引号字符和美元符号)。
To insert a variable in the middle of a single quoted text, you have to end the single quote, then concatenate with the double quoted variable, and re-open the single quote to continue the text: 'foo bar'"$variable"'more foo'.
要在单引号文本中间插入一个变量,您必须结束单引号,然后与双引号变量连接,并重新打开单引号以继续文本:'foo bar'"$variable"'more foo'。
回答by pbaranski
Solution tested with https://httpbin.org/and inline bash script
1.For variables without spaces in it i.e. 1:
Simply add 'before and after $variablewhen replacing desired
string
使用https://httpbin.org/和内联 bash 脚本测试的解决方案
1.对于没有空格的变量,即1:在替换所需字符串时
只需在'前后添加$variable
for i in {1..3}; do \
curl -X POST -H "Content-Type: application/json" -d \
'{"number":"'$i'"}' "https://httpbin.org/post"; \
done
2.For input with spaces:
Wrap variable with additional "i.e. "el a":
2.对于带空格的输入:
用额外的"ie包装变量"el a":
declare -a arr=("el a" "el b" "el c"); for i in "${arr[@]}"; do \
curl -X POST -H "Content-Type: application/json" -d \
'{"elem":"'"$i"'"}' "https://httpbin.org/post"; \
done
Wow works :)
哇作品:)
回答by Che Ruisi-Besares
Curl can post binary data from a file so I have been using process substitution and taking advantage of file descriptors whenever I need to post something nasty with curl and still want access to the vars in the current shell. Something like:
Curl 可以从文件中发布二进制数据,所以我一直在使用进程替换并利用文件描述符,每当我需要使用 curl 发布一些令人讨厌的东西并且仍然想要访问当前 shell 中的变量时。就像是:
curl "http://localhost:8080" \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
--data @<(cat <<EOF
{
"me": "$USER",
"something": $(date +%s)
}
EOF
)
This winds up looking like --data @/dev/fd/<some number>which just gets processed like a normal file. Anyway if you wanna see it work locally just run nc -l 8080first and in a different shell fire off the above command. You will see something like:
这最终看起来就像--data @/dev/fd/<some number>像普通文件一样被处理。无论如何,如果你想看到它在本地工作,只需nc -l 8080先运行,然后在不同的 shell 中启动上述命令。你会看到类似的东西:
POST / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.43.0
Accept: application/json
Content-Type:application/json
Content-Length: 43
{ "me": "username", "something": 1465057519 }
As you can see you can call subshells and whatnot as well as reference vars in the heredoc. Happy hacking hope this helps with the '"'"'""""'''""''.
如您所见,您可以在heredoc 中调用子shell 等以及引用变量。快乐黑客希望这有助于'"'"'""""'''""''.
回答by glyph
A few years late but this might help someone if you are using eval or backtick substitution:
晚了几年,但如果您使用 eval 或反引号替换,这可能会对某人有所帮助:
postDataJson="{\"guid\":\"$guid\",\"auth_token\":\"$token\"}"
Using sed to strip quotes from beginning and end of response
使用 sed 从响应的开头和结尾去除引号
$(curl --silent -H "Content-Type: application/json" https://${target_host}/runs/get-work -d ${postDataJson} | sed -e 's/^"//' -e 's/"$//')
回答by glyph
- the info from Sir Athos worked perfectly !!
- 来自阿索斯爵士的信息非常有效!!
Here's how I had to use it in my curl script for couchDB. It really helped out a lot. Thanks!
这是我必须在我的 couchDB 的 curl 脚本中使用它的方式。它真的帮了很多忙。谢谢!
bin/curl -X PUT "db_domain_name_:5984/_config/vhosts/.couchdb" -d '"/'""'/"' --user "admin:*****"
回答by xgMz
Here's what actually worked for me, after guidance from answers here:
在此处的答案指导下,以下是对我真正有用的方法:
export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
"name": $BASH_VARIABLE,
"something": [
"value1",
"value2",
"value3"
]
}
EOF
)" -H 'Content-Type: application/json'
回答by abyrd
Existing answers point out that curl can post data from a file, and employ heredocs to avoid excessive quote escaping and clearly break the JSON out onto new lines. However there is no need to define a function or capture output from cat, because curl can post data from standard input. I find this form very readable:
现有答案指出 curl 可以从文件中发布数据,并使用 heredocs 来避免过多的引号转义并清楚地将 JSON 分解为新行。然而,不需要定义函数或捕获 cat 的输出,因为 curl 可以从标准输入发布数据。我发现这个表格非常易读:
curl -X POST -H 'Content-Type:application/json' --data '$@-' ${API_URL} << EOF
{
"account": {
"email": "$email",
"screenName": "$screenName",
"type": "$theType",
"passwordSettings": {
"password": "$password",
"passwordConfirm": "$password"
}
},
"firstName": "$firstName",
"lastName": "$lastName",
"middleName": "$middleName",
"locale": "$locale",
"registrationSiteId": "$registrationSiteId",
"receiveEmail": "$receiveEmail",
"dateOfBirth": "$dob",
"mobileNumber": "$mobileNumber",
"gender": "$gender",
"fuelActivationDate": "$fuelActivationDate",
"postalCode": "$postalCode",
"country": "$country",
"city": "$city",
"state": "$state",
"bio": "$bio",
"jpFirstNameKana": "$jpFirstNameKana",
"jpLastNameKana": "$jpLastNameKana",
"height": "$height",
"weight": "$weight",
"distanceUnit": "MILES",
"weightUnit": "POUNDS",
"heightUnit": "FT/INCHES"
}
EOF

