我正在尝试构建一个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”已被截断。谁能让我知道我在这里做错了什么?
答案 0 :(得分:5)
使用更多的报价!
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