传递给curl的-d选项的Shell变量无法正常工作

时间:2017-01-26 23:06:24

标签: php bash curl

我正在尝试在CURL命令中使用PATCH方法使用-d选项。我的代码如下:     IFS =" &#34 ;;     读线时     做       阵列=($线);
      json_string =" {\" attributes \":{\" member_id \":$ {array [0]},\" is_student \&#34 ;:$ {array [1]}}}"

  curl -v --fail --silent --show-error --request PATCH -H "Content-Type: application/json"  --user $API_KEY:$API_SECRET -d $json_string $PROFILE_URL/${array[0]} --trace-ascii /dev/stdout
done < $file

输入文件是txt文件,它有两列: 123 0
我使用 space 作为行分隔符。 问题是当我使用$ json_string时出现此错误:

    == Info: Rebuilt URL to: "attributes":/
    == Info: Could not resolve host: "attributes"
    == Info: Closing connection 0
    curl: (6) Could not resolve host: "attributes"
    curl: (3) [globbing] unmatched brace in column 1
    == Info: Rebuilt URL to: "member_id":/
    == Info: Could not resolve host: "membe

r_id"
== Info: Closing connection 1
curl: (6) Could not resolve host: "member_id"
== Info: Rebuilt URL to: 123,/
== Info: Could not resolve host: 123,

=> Send data, 2 bytes (0x2)
0000: "{
== Info: upload completely sent off: 2 out of 2 bytes

但是当我使用&#34; $ json_string&#34; (用双引号包围的$ json_string)它工作正常。任何想法?

1 个答案:

答案 0 :(得分:1)

将变量json_string括在双引号中以防止shell分词:

curl -v --fail --silent --show-error --request PATCH -H "Content-Type:application/json"  --user "$API_KEY:$API_SECRET" -d "$json_string" "$PROFILE_URL/${array[0]}" --trace-ascii /dev/stdout

您可以通过以下方式直接将数据线读入数组:

#!/bin/bash

while read -a line; do
  # your logic
done < "$file"

点击此处了解有关吐痰的更多信息:Bash Best Practices - Quoting