如何使用Bash在单引号内回显变量? [英] How to echo variable inside single quotes using Bash?
问题描述
用户.我想使用bash脚本运行curl命令. (以下命令在终端中可以正常运行)
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
但是无法在bash中运行此命令.当在变量($ final)中指定安装点值时.
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字符串周围使用双引号并转义内部双引号来实现此目的,例如:
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
如评论中所述,一种更可靠的方法是使用诸如jq
之类的工具来生成JSON:
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
这篇关于如何使用Bash在单引号内回显变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!