shell bash,如何在单引号内回显变量(How to echo variable inside single quotes using Bash?)

编程入门 行业动态 更新时间:2024-10-26 01:34:21
shell bash,如何在单引号内回显变量(How to echo variable inside single quotes using Bash?)

users.I想用bash脚本运行一个curl命令。 (下面的命令在终端中完美工作)

curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":"/gua-la-autentica-1426251559"}' http://127.0.0.1:5000/connect

但无法在bash中运行此命令。 当在一个变量($ final)中给出安装点值时。

final="/gua-la-autentica-1426251559" curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":'$final'}' http://127.0.0.1:5000/connect

有人可以帮助我,如何在单引号内回显变量?

users.I want to run a curl command with a bash script. (below command works perfectly in terminal)

curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":"/gua-la-autentica-1426251559"}' http://127.0.0.1:5000/connect

But unable to run this command in bash. When mountpoint value is given in a variable($final).

final="/gua-la-autentica-1426251559" curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":'$final'}' http://127.0.0.1:5000/connect

Could someone please help me, how to echo variable inside single quotes?

最满意答案

JSON字符串值应该引用,参数扩展也应该引用。 您可以通过在整个JSON字符串周围使用双引号并转义内部双引号来实现此目的,如下所示:

curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect

正如评论中所提到的,更强大的方法是使用jq等工具生成JSON:

json=$(jq -n --arg final "$final" '{ mountpoint: $final }') curl -i -H "Content-Type: application/json" -X POST -d "$json" http://127.0.0.1:5000/connect

JSON string values should be quoted and so should parameter expansions. You can achieve this by using double quotes around the entire JSON string and escaping the inner double quotes, like this:

curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect

As mentioned in the comments, a more robust approach would be to use a tool such as jq to generate the JSON:

json=$(jq -n --arg final "$final" '{ mountpoint: $final }') curl -i -H "Content-Type: application/json" -X POST -d "$json" http://127.0.0.1:5000/connect

更多推荐

本文发布于:2023-07-17 04:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1139251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   单引号   如何在   内回显   shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!