0

I'm trying to pass --data-raw options to a curl inside bash function, but I get option unknown error.

function api_call () {
    local data="$5"
        echo $(curl -L -X $1 "https://api.datadoghq.com/api/v1/monitor/$2" \
          -H "Accept: application/json" \
          -H "Content-Type: application/json" \
          -H "DD-API-KEY: $3" \
          -H "DD-APPLICATION-KEY: $4" \
          $data)
}

I call it with

api_call "PUT" $monitor_id $DATADOG_API_KEY $DATADOG_APP_KEY $query

my query value is

query="--data-raw '{"query":"sum(last_1m):avg:application.health{application.health:healthy,c_name:nname,!source:service-full-1} by {source}.as_count() < 60"\}')"

but it doesn't matter what I put in data, it doesn't get accepted when calling the function. It works as intended if I simply do a curl.

What am I missing? thanks!

Kurse
  • 1
  • 2
  • 2
    [How can we run a command stored in a variable?](https://unix.stackexchange.com/q/444946/108618) and [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/q/131766/108618) Your `query` contains quotes you don't want, doesn't contain quotes you want; unquoted `$query` gets split where you don't expect. – Kamil Maciorowski Nov 21 '22 at 17:08
  • Also (because of the reasons Kamil noted), that `query=...` assignment won't work, it'll likely croak on the `(` or the `!` (depending on if history expansion is enabled, and maybe on the shell too). It'd be better if you could show the _exact_ code you're running, and the exact output you get, including the version where it works if you "simply do X". Not that it looks like it'd matter much here, at least until you fix the quoting issues etc. – ilkkachu Nov 21 '22 at 19:32
  • (Also note that `echo $(foo)` is pretty much the same as just `foo`, except for trashing some whitespace and expanding globs) – ilkkachu Nov 21 '22 at 19:32

1 Answers1

0

As everyone in the comments pointed out that shell splits the variable and it will not be ran as a command. Thank you @Kamil Maciorowski for the very useful links that explain this in detail. Why does my shell script choke on whitespace or other special characters? How can we run a command stored in a variable?

Kurse
  • 1
  • 2