命令替换中的变量扩展为多个参数

Variable in command substitution is expanded into multiple arguments

我试图在 bash 脚本中创建一个方法,它应该能够执行可变数量的 headers 的 curl 操作,但是我似乎陷入了困境curl 命令将 header 参数视为多个参数,因为它们包含 spaces.

当我 运行 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 (, ...)
    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

我注意到,尽管 header 是 -H "Content-Type: application/json,但 curl 显示 Could not resolve host: application。我怀疑由于 Content-Type:application/json 之间的 space,它将参数分成两部分。

我尝试以各种组合方式混合和匹配引号和双引号,但没有任何效果。

@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"
}