且构网

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

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

更新时间:2023-10-06 14:48:10

变量不会在单引号内扩展.用双引号重写:

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