bash 如何在 curl 命令中将标头作为参数传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34617543/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:04:54  来源:igfitidea点击:

How to pass a header as argument in curl command?

bashshellcurl

提问by Alex S

I am attempting to do a curl command that uses a predefined variable as a header.

我正在尝试执行使用预定义变量作为标头的 curl 命令。

header='-H "Content-Type: application/json" -H "userGUID: 7feb6e62-35da-4def-88e9-376e788ffd97" -H "Content-Length: 51"'

And this is essentially the curl command

这本质上是 curl 命令

curl $header -w "http code: %{http_code}\n" -X POST -d $BODY $URL 

Which then returns the error message

然后返回错误消息

rl: (6) Could not resolve host: application
curl: (6) Could not resolve host: 7feb6e62-35da-4def-88e9-376e788ffd97"
curl: (6) Could not resolve host: 51"

This works as expected

这按预期工作

curl -H "Content-Type: application/json" -H "userGUID: 7feb6e62-35da-4def-88e9-376e788ffd97" -H "Content-Length: 51" -w "http code: %{http_code}\n" -X POST -d $BODY $URL 

The reason I'm trying to pass the header as a variable is because I'm writing a script that loops through and array, but currently this does not work with headers for some reason. There is no issue passing arguments for body.

我试图将标头作为变量传递的原因是因为我正在编写一个循环遍历数组的脚本,但目前由于某种原因这不适用于标头。为 body 传递参数没有问题。

回答by wafflecat

Be aware that variable expansion in bash can catch people off guard easily.

请注意,bash 中的变量扩展很容易让人措手不及。

A pretty good rule of thumb is to put double quotes around any variable you want to expand like curl "$header" -w "http code: %{http_code}\\n" -X POST -d "$BODY" "$URL".

一个很好的经验法则是在您想要扩展的任何变量周围加上双引号,例如curl "$header" -w "http code: %{http_code}\\n" -X POST -d "$BODY" "$URL".

Bash always expands $SOMETHINGvariables if they appear on their own, or if they appear in double quotes. (Not if they appear in single quotes).

$SOMETHING如果变量单独出现,或者如果它们出现在双引号中,Bash 总是扩展变量。(如果它们出现在单引号中则不会)。

When expanded withdouble quotes they are treated as a single "token" by the shell, no matter what.

双引号扩展时它们被外壳视为单个“标记”,无论如何。

When expanded withoutdouble quotes they will be parsed as if you had typed their contents instead of the variable. So - if that variable had spaces, that may mean the shell will treat those as separators between arguments.

没有双引号的情况下展开时它们将被解析,就像您输入了它们的内容而不是变量一样。所以 - 如果该变量有空格,那可能意味着 shell 会将它们视为参数之间的分隔符。