1

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Nice; it may make it clearer what happens to write args+=(-d "$arg_name=$arg_value") (double quotes around $arg_name=$arg_value as a whole) - the add-to-array assignment effectively adds 2 elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.