0

I want to send data to a server via curl. The script has to first build the curl command by appending several parameters. Something like this:

# set other params...

param4_name="param4"
param4_value="Hello world"

params=""

# append other params to $params...

if [[ ! -z "$param4_value" ]]; then
    params="$params --data-urlencode \"$param4_name=$param4_value\" "
fi

response="$(curl \
    $params \
    --get \
    $my_url/test)"

When I use this code, however, the server receives the curl request as:

HTTP-Request: GET /test?"param4=Hello HTTP/1.1

(The " is included in the key and " world" is missing in the value.)

If I adjust the code to use:

if [[ ! -z "$param4_value" ]]; then
    params="$params --data-urlencode $param4_name="$param4_value" "
fi

The server receives this:

HTTP-Request: GET /test?param4=Hello HTTP/1.1

(" world" is missing in the value.)

How do I adjust the bash code so that the server receives this request instead:

HTTP-Request: GET /test?param4=Hello%20World HTTP/1.1

I'm amenable to using this solution. But is there a "neater" way to do this without resorting to using a function, an embedded curl call, or perl/sed/awk/etc?

hermit.crab
  • 852
  • 1
  • 8
  • 20
  • 2
    Storing commands (or lists of arguments for commands) in plain variables doesn't work right; either just *use* the arguments on the actual command (i.e. don't try to collect them first), or if you need to store them first use an array (with each arg in a separate element). See ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948) and [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) (and avoid all suggestions involving `eval`). – Gordon Davisson Apr 05 '22 at 02:46

0 Answers0