How could I curl for a request with headers in shell scripting

谁说我不能喝 提交于 2019-11-29 15:40:53
randomir

Single quotes ' (you're using in -d argument) preserve the literal value of each character, including the $ (see this SO answer), and that's why your variable query_string is not being expanded.

Try this:

~$ query_string="my query"

~$ echo '$query_string'
$query_string

~$ echo "$query_string"
my query

So, you need to use double quotes " if you wish your variables to expand to its values.

However, in order to nest double quotes (inside other double quotes), as in you JSON data, you must either:

  1. escape the inner quotes, like this:

    ~$ echo "{\"query\": \"$query_string\"}"
    {"query": "my query"}
    

    but that gets very ugly, very soon; or

  2. concatenate strings under alternating single and double quotes, like this:

    ~$ echo '{"query": "'"$query_string"'"}"'
    {"query": "my query"}"
    

    which may be more readable for shorter strings; or

  3. use a here-document:

    ~$ read query <<-END
    {"query": "$query_string"}
    END
    
    ~$ echo "$query"
    {"query": "my query"}
    

    Here-documents are particularly convenient for longer documents in which you wish for parameter/variable expansion, command substitution, arithmetic expansion, etc.

In summary, after defining your JSON query with one of the above ways (perhaps via a here-document), you can write your curl command like this:

curl -s -X POST -H 'Content-Type: application/json' 'http://www.dummy.com/projectname/page_relevance' -d "$query"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!