Embedding quotes in a variable's value, like APISTRING+="--data-urlencode \"picture=$\" "
does not work right. When you try to use $APISTRING
, bash parses quotes before expanding the variable's value, and it doesn't rescan for "new" quotes after expansion. As a result, the quotes are treated as part of the string, rather than as delimiters around the string.
The best solution for things like this is to use an array to store the command options:
APISTRING=() if [ ! -z $ ]; then APISTRING+=(--data-urlencode "picture=$");fi if [ ! -z $ ]; then APISTRING+=(--data-urlencode "additional_info=$");fi curl -v -X "POST" --url "https://example.org/api" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" "$"
Note that arrays are not available in all POSIX shells, so you should only use this in scripts you explicitly use bash for (i.e. a shebang of either #!/bin/bash
or #!/usr/bin/env bash
, not #!/bin/sh
). Also, the syntax is very picky; don't leave off any of the parentheses in the assignments, the double-quotes, or the [@]
when expanding the array.
BTW, there is another possible solution. Rather than accumulating the optional options beforehand, you can use conditional expansion to include them on the spot:
curl -v -X "POST" --url "https://example.org/api" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \ $"} \ $"}
Here, the :+
expansion tells bash to check whether the variable's nonblank, and if it is to not use it, but an alternate value: the quoted version of the variable with the appropriate prefix.