如何在 bash 脚本中的 curl 调用中使用变量 [英] How can I use a variable in curl call within bash script

查看:39
本文介绍了如何在 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

这篇关于如何在 bash 脚本中的 curl 调用中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆