Bash中的指挥大楼和字符串逃逸



我正在尝试构建一个 Bash 脚本,该脚本将从命令行获取参数以及硬编码参数并将它们传递给函数,该函数又将构造对 curl 的调用并执行 HTTP POST。 不幸的是,当我尝试传递带有空格的字符串时,脚本会破坏字符串,并且最终对 curl 的调用无法按正确的顺序传递参数:

#!/bin/bash
API_URL="http://httpbin.org/"
docurl() {
    arg1=$1
    shift
    arg2=$1
    shift
    args=()
    while [ "$1" ]
    do
        arg_name="$1"
        shift
        arg_value="$1"
        shift
        args+=(-d $arg_name="$arg_value")
    done
    curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1=$arg1 -d arg2=$arg2 ${args[@]} ) 2>/dev/null
    echo "$curl_result"
}
docurl foo1 foo2 title "$1" body "$2"

脚本调用如下所示:

test2.sh "Hello" "Body of the message"

脚本的输出是这样的:

{
  "form": {
    "body": "Body",
    "arg1": "foo1",
    "arg2": "foo2",
    "title": "Hello"
  },
  "headers": {
    "Host": "httpbin.org",
    "Connection": "close",
    "Content-Length": "41",
    "User-Agent": "curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3",
    "Content-Type": "application/x-www-form-urlencoded",
    "Accept": "*/*"
  },
  "files": {},
  "data": "",
  "url": "http://httpbin.org/post",
  "args": {},
  "origin": "xxx.xxx.xxx.xxx",
  "json": null
}

如您所见,在 form 元素中,字段"body"和"title"已被截断。谁能告诉我我在这里做错了什么?

多用一点引号!

    args+=(-d "$arg_name"="$arg_value")

和:

curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1="$arg1" -d arg2="$arg2" "${args[@]}" ) 2>/dev/null