如何在 bash 脚本中的 curl 调用中使用变量

问题描述:

我有这个简单的任务,我已经花了几个小时试图弄清楚如何在我的 bash 脚本中的 curl 调用中使用变量:

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}"}'

这是输出 ${message},字面意思是因为它在单引号内.如果我更改引号并将 double 放在外面,single 在里面,它会显示命令未找到:Hello 然后命令未找到:那里.

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?

变量不在单引号内展开.使用双引号重写:

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.

另一种变化可能是:

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

这个从单引号中跳出来,将 ${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