且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-06 14:52:22

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

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