0

I'm trying to run some REST API call via curl, but I'm facing some issue when it comes to generating that curl command using bash.

Please see my example code:

#!/bin/bash

CURL_ARGS="-H \"Content-Type: application/json\" --data @somefile.json"
# further variables are set here as well

set -o xtrace   # print command before execution
curl -k -X ${PROTOCOL} -u "${CICD_USER}:${CICD_PW}" ${CURL_ARGS} ${URL} -v

Output of xtrace:

+ curl -k -X POST -u redacted:redacted -H '"Content-Type:' 'application/json"' --data @somefile.json https://redacted/rest/v1/group/import -v

The curl command obviously fails because ${CURL_ARGS} is not resolved correctly.

I'm confused about the expansion of ${CURL_ARGS}. Why is the string expanded to -H '"Content-Type:' 'application/json"'?

What I'd expect is to generate the curl command like this:

curl -k -X POST -u redacted:redacted -H "Content-Type: application/json" --data @somefile.json https://redacted/rest/v1/group/import -v
dovregubben
  • 364
  • 2
  • 16
  • The shell expands variables *after* parsing quotes and escapes, so this doesn't work; either use an array, or just don't store multiple arguments in a single variable. See [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 ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables) (but avoid all suggestions involving `eval`). – Gordon Davisson Nov 17 '21 at 07:24
  • Thanks for the links. I updated my script and now use the `${var:+..}` parameter expansion, which works fine. I have to admit that I still don't really understand how that variable expansion, parsing and escaping works, but I found a solution that does the job... – dovregubben Nov 17 '21 at 08:58

0 Answers0