问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/58028474/curl-quotes-and-variable-trouble