Curl quotes and variable trouble [duplicate]

杀马特。学长 韩版系。学妹 提交于 2021-01-29 19:33:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!