如何通过并正确转义HTTP标头/参数以在bash脚本中卷曲?在shell上正常工作:-/

时间:2018-12-03 04:17:03

标签: bash curl

我跑步

/usr/local/bin/curl -V
    curl 7.63.0-DEV (x86_64-pc-linux-gnu) libcurl/7.63.0-DEV OpenSSL/1.1.1a zlib/1.2.11 brotli/1.0.3 libidn2/2.0.5 libpsl/0.20.2 (+libidn2/2.0.5) libssh2/1.8.1_DEV nghttp2/1.36.0-DEV

bash --version
    GNU bash, version 4.4.23(1)-release (x86_64-suse-linux-gnu)

此对api端点的curl查询在shell上完美运行

TOKEN="testtoken" /usr/local/bin/curl \
 -H "content-type: application/json" \
 -H "Authorization: Bearer ${token}" \
-X GET ${url}/endpoint

&返回预期结果,例如

{
  "result" : "blah"
}

仅命令的最后一行有所不同。我想将其余的内容包装到bash便利脚本中。

阅读后尽力逃避地狱

  

我试图将命令放入变量中,但是复杂的情况总是会失败!   http://mywiki.wooledge.org/BashFAQ/050

和@ stackoverflow

pass an array of headers to curl into a bash script

我整理了这个脚本,

cat test.sh
    #!/bin/bash
    token="testtoken" 

    mk_keyval() {
      local mkey=${1}
      local mval=${2}
      echo "\"${mkey}: ${mval}\""
    }

    mk_hdrs() {
      HDR=()
      HDR[0]=$(mk_keyval "content-type" "application/json")
      HDR[1]=$(mk_keyval "Authorization" "Bearer ${token}")
    }

    mk_hdrs
    echo -e "${HDR[@]/#/-H }\n"
    /usr/local/bin/curl "${HDR[@]/#/-H }" "@"

在执行程序上

bash ./test.sh -X GET ${url}/endpoint

它返回

-H "content-type: application/json" -H "Authorization: Bearer testtoken"

curl: (6) Could not resolve host:

echo头与上面的shell用法相匹配,

 -H "content-type: application/json" \
 -H "Authorization: Bearer ${token}" \

如何正确执行脚本的转义,使其执行与shell命令相同的内容?

1 个答案:

答案 0 :(得分:2)

我认为问题出在最后一行,您实际上在它们上执行了curl命令。见

/usr/local/bin/curl "${HDR[@]/#/-H }" "@"
#                                     ^^^ this is an incorrect token, should have been "$@"

bash中的实际位置参数列表是"$@",应该在您的命令中将其用作

/usr/local/bin/curl "${HDR[@]/#/-H }" "$@"