我試圖在 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。
我試圖以各種組合混合和匹配引號和雙引號,但沒有任何效果。
uj5u.com熱心網友回復:
@GordonDavisson 是對的,你必須把你的header_options放在一個陣列中。請注意,在陣列"${header_options[@]}"為空時使用陣列會導致curl命令中的引數為空,但是您可以通過將整個命令存盤在另一個陣列中來解決此問題。
submit_request () {
local -a header_options
for arg; do header_options =(-H "$arg"); done
local -a curl_command=( \
curl \
-X POST \
localhost:9200/index-template/globalmetadata \
--write-out '%{http_code}' \
--silent \
--output /dev/null \
--verbose \
--data '@/home/mat/globalmetadata.json' \
"${header_options[@]}" \
)
local response=$( "${curl_command[@]}" )
printf '%s\n' "$response"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359477.html
上一篇:如何從標準輸出執行命令?
