使用 bash 变量将多个标头传递给 curl 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46449949/
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 a bash variable to pass multiple headers to curl command
提问by Maxime.D
I would like to make curl
request with multiple headers.The solution would be to make this command :
我想curl
使用多个标头发出请求。解决方案是执行以下命令:
curl -H "keyheader: value" -H "2ndkeyheader: 2ndvalue" ...
My goal is to use only one variable with all the headers like :
我的目标是只使用一个带有所有标题的变量,例如:
headers='-H "keyheader: value" -H "2ndkeyheader: 2ndvalue" '
curl $headers
to send
发送
curl -H "keyheader: value" -H "2ndkeyheader: 2ndvalue"
Currently, the problem is : I can use '
or "
to declare my string, but bash
tries to run what's after "-H"
as arguments and then answers :
目前,问题是:我可以使用'
或"
声明我的字符串,但bash
尝试将后面的内容"-H"
作为参数运行,然后回答:
command unknown
Would like to know what is going wrong here.
想知道这里出了什么问题。
回答by Inian
You just need to use an array and nota variable to pass the quoted strings.
您只需要使用数组而不是变量来传递带引号的字符串。
declare -a curlArgs=('-H' "keyheader: value" '-H' "2ndkeyheader: 2ndvalue")
and now pass this array fully that way, the array expansion(with double-quotes) takes care of the arguments within double-quotes to be not split while passing.
现在以这种方式完全传递这个数组,数组扩展(带双引号)负责处理双引号内的参数,以便在传递时不被拆分。
curl "${curlArgs[@]}"
For more insight into why putting the args in your variables fail, see BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail!
有关为什么将 args 放入变量失败的更多见解,请参阅BashFAQ/050 - 我正在尝试将命令放入变量中,但复杂的情况总是失败!