如何在curl命令中将标头作为参数传递? [英] How to pass a header as argument in curl command?

查看:441
本文介绍了如何在curl命令中将标头作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

这基本上是curl命令

And this is essentially the curl command

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

然后返回错误消息

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"

这可以按预期工作

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 

我尝试传递标头的原因之所以将其作为变量,是因为我正在编写一个遍历and数组的脚本,但是由于某种原因,当前它不适用于标头。

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.

推荐答案

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

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

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

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".

Bash始终会扩展 $ SOMETHING 变量,如果它们单独出现或用双引号引起来。 (如果它们用单引号引起来,则不是。)

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

当用双引号扩展 时,它们会被shell视为一个令牌,

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

当展开而没有双引号时,它们将被解析,就像您键入内容而不是变量一样。所以-如果该变量具有空格,则可能意味着shell将把它们当作参数之间的分隔符。

When expanded without double 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.

这篇关于如何在curl命令中将标头作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆