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

标签 bash shell curl

<分区>

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

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

这本质上就是 curl 命令

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 

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

最佳答案

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

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

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

当用双引号展开时,它们会被 shell 视为单个“标记”,无论如何。

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

关于bash - 如何在 curl 命令中将 header 作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34617543/

相关文章:

curl - 如何向elasticsearch中插入数据

c - 无法使用 libcurl 将 HTTP PUT 发送到 django-piston

string - 线路操作和排序

git - 在 Bash 命令提示符下添加 git 分支

shell 脚本 ssh 命令退出状态

linux - 编写 bash 脚本

Python os.path.isdir 对于点返回 true

PHP - 无法执行我的 BASH 脚本来启动我的 C++ 二进制文件

linux - 复杂的 bash 管道在跳跃中工作

ruby-on-rails - 在 Windows 中设置 Curb