0

I need to run a curl command from a shell script that reads a file of host names. Here is the script that does not work:

#!/bin/sh

HOST="HOSTNAME"

curl https://SOME_URL -H 'Content-Type: application/json' -H 'API-Key: SOME_KEY' --data-binary '{"query":"{\n  actor {\n    entitySearch(query: \"name LIKE \u0027$HOST\u0027\") {\n      results {\n        entities {\n          guid\n        }\n      }\n    }\n  }\n}\n", "variables":""}'

The problem is name LIKE \u0027$HOST\u0027

I need the \u0027 for the single quote character.

If I use an actual host name instead of the variable it works fine.

I tried curly braces around the variable and that doesn't work.

Jimmy D
  • 5,282
  • 16
  • 54
  • 70
  • 1
    curl or u0027 have nothing to do with this. You have `'...$HOST...'`. Variables within single quotes are not expanded. You may want to use `'...'"${HOST}"'...'`. – n. m. could be an AI Sep 20 '19 at 12:40

1 Answers1

0

The issue is because of your use of a single quotes ' to send your --data-binary field. By design, bash variables are not expanded inside of single quotes. You could either reverse your usage of single and double quotes, or simply concatenate the expanded variable by placing single quotes around your bash variable, as such:

curl https://SOME_URL -H 'Content-Type: application/json' -H 'API-Key: SOME_KEY' --data-binary '{"query":"{\n  actor {\n    entitySearch(query: \"name LIKE \u0027'$HOST'\u0027\") {\n      results {\n        entities {\n          guid\n        }\n      }\n    }\n  }\n}\n", "variables":""}

As an additional note, it is preferred to encapsulate bash variables representing strings inside of double quotes, such as "$HOST". This is because the text following a reference to a bash variable is removed if that variable does not exist; however, referencing a quoted bash variable that doesn't exist will simply return an empty string instead of removing the rest of the command. I've left the solution above in the unquoted form so it is easier to see the changes, but it is good practice to use the quoted form in scripts.

h0r53
  • 3,034
  • 2
  • 16
  • 25
  • Perfect, thank you! Now how can I grab JUST the guid text that gets returned, all in the same command? ;-) – Jimmy D Sep 20 '19 at 13:18
  • You could store the result in another variable, or pipe the command into a grep statement. – h0r53 Sep 20 '19 at 13:28