【发布时间】:2021-11-10 22:09:20
【问题描述】:
我尝试在 bash 脚本中创建一个方法,该方法应该能够使用可变数量的标头执行 curl 操作,但是我似乎陷入了 curl 命令将标头参数视为多个参数的问题中它们包含空格。
当我在 bash 中运行以下行时,我得到 201 响应:
response=$($executable -X POST localhost:9200/index-template/globalmetadata --write-out '%{http_code}' --silent --output /dev/null --verbose --data "@${full_path}" -H "Content-Type: application/json" )
如果我运行以下命令:
#!/bin/bash
submit_request () {
full_path=/home/mat/globalmetadata.json
header_option=""
header_options=""
for header in "${@:1}"; do # looping over the elements of the $@ array ($1, $2...)
header_option=$(printf " -H %s" "$header")
header_options=$(printf '%s%s' "$header_options" "$header_option")
done
echo Headers: $header_options
executable=curl
#response=$($executable -X POST localhost:9200/index-template/globalmetadata --write-out '%{http_code}' --silent --output /dev/null --verbose --data "@${full_path}" -H "Content-Type: application/json" )
response=$($executable -X POST localhost:9200/index-template/globalmetadata --write-out '%{http_code}' --silent --output /dev/null --verbose --data "@${full_path}" $header_option )
echo $response
}
submit_request "\"Content-Type: application/json\""
我得到这个输出:
Headers: -H "Content-Type: application/json"
======= 3
* Trying 127.0.0.1:9200...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9200 (#0)
> POST /index-template/globalmetadata HTTP/1.1
> Host: localhost:9200
> User-Agent: curl/7.68.0
> Accept: */*
> Content-Length: 3232
> Content-Type: application/x-www-form-urlencoded
> Expect: 100-continue
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 100 Continue
} [3232 bytes data]
* We are completely uploaded and fine
* Mark bundle as not supporting multiuse
< HTTP/1.1 406 Not Acceptable
< X-elastic-product: Elasticsearch
< content-type: application/json; charset=UTF-8
< content-length: 97
<
{ [97 bytes data]
* Connection #0 to host localhost left intact
* Could not resolve host: application
* Closing connection 1
406000
我注意到的是,即使标题是 -H "Content-Type: application/json,curl 也会显示 Could not resolve host: application。我怀疑由于Content-Type: 和application/json 之间的空格,它会将参数分成两部分。
我尝试在各种组合中混合和匹配引号和双引号,但没有任何效果。
【问题讨论】:
-
将您的
curl命令中的$header_option替换为"$header_option"? -
将参数列表存储为纯字符串仅适用于非常简单的情况;对于这样的事情,您需要使用一个数组,每个参数都存储为一个单独的数组元素(并在展开数组时正确引用)。见this question 和BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!
标签: bash shell command-substitution