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

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

本文介绍了如何在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},实际上是因为它在单引号内.如果我更改引号并在外部加双且在内部加单,则表示找不到命令:您好,然后找不到命令:那里.

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调用中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:22