Reputation: 13
I am trying to build a Bash script that will take arguments from the command line as well as hard-coded arguments and pass them to a function, which in turn will construct a call to curl and perform an HTTP POST. Unfortunately, when I try passing strings with spaces in them, the script mangles the strings and the eventual call to curl fails to pass the arguments in the right order:
#!/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"
The script invocation would be something like this:
test2.sh "Hello" "Body of the message"
The output of the script as it stands is this:
{
"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
}
As you can see, in the form
element, the fields "body" and "title" have been truncated. Can anybody let me know what on what I'm doing wrong here?
Upvotes: 1
Views: 205
Reputation: 5327
Use a bit more quotes!
args+=(-d "$arg_name"="$arg_value")
And:
curl_result=$( curl -qSfs "$API_URL/post" -X POST -d arg1="$arg1" -d arg2="$arg2" "${args[@]}" ) 2>/dev/null
Upvotes: 5