How can I use a variable in curl call within bash

2019-03-05 11:15发布

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="Hello there"
curl -X POST -H 'Content-type: application/json' --data '{"text": "${message}"}'

This is outputting ${message}, literally because it's inside a single quote. If I change the quotes and put double outside and single inside, it says command not found: Hello and then command not found: there.

How can I make this work?

标签: bash shell curl
2条回答
Explosion°爆炸
2楼-- · 2019-03-05 11:25

Variables are not expanded within single-quotes. Rewrite using double-quotes:

curl -X POST -H 'Content-type: application/json' --data "{\"text\": \"${message}\"}"

Just remember that double-quotes within double-quotes have to be escaped.

Another variation could be:

curl -X POST -H 'Content-type: application/json' --data '{"text": "'"${message}"'"}'

This one breaks out of the single quotes, encloses ${message} within double-quotes to prevent word splitting, and then finishes with another single-quoted string. That is:

... '{"text": "'"${message}"'"}'
    ^^^^^^^^^^^^
    single-quoted string


... '{"text": "'"${message}"'"}'
                ^^^^^^^^^^^^
                double-quoted string


... '{"text": "'"${message}"'"}'
                            ^^^^
                            single-quoted string
查看更多
相关推荐>>
3楼-- · 2019-03-05 11:36

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.

查看更多
登录 后发表回答