How can I use a variable in curl call within bash script

前端 未结 2 465
借酒劲吻你
借酒劲吻你 2020-12-20 16:21

I have this simple task and I\'ve spent a few hours already trying to figure out how can I use a variable inside a curl call within my bash script:

message=\         


        
2条回答
  •  借酒劲吻你
    2020-12-20 16:51

    While the other post (and shellcheck) correctly points out that single quotes prevent variable expansion, the robust solution is to use a JSON tool like jq:

    message="Hello there"
    curl -X POST -H 'Content-type: application/json' \
        --data "$(jq -n --arg var "$message"  '.text = $var')"
    

    This works correctly even when $message contains quotes and backslashes, while just injecting it in a JSON string can cause data corruption, invalid JSON or security issues.

提交回复
热议问题