use*_*052 2 bash shell json curl
我想用bash脚本运行curl命令。(以下命令在终端中可以正常运行)
curl -i -H "Content-Type: application/json" -X POST -d '{"mountpoint":"/gua-la-autentica-1426251559"}' http://127.0.0.1:5000/connect
Run Code Online (Sandbox Code Playgroud)
但是无法在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
Run Code Online (Sandbox Code Playgroud)
有人可以帮我吗,如何在单引号内回显变量?
JSON字符串值应加引号,参数扩展也应加引号。您可以通过在整个JSON字符串周围使用双引号并转义内部双引号来实现此目的,如下所示:
curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect
Run Code Online (Sandbox Code Playgroud)
如评论中所述,更健壮的方法是使用一种工具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
Run Code Online (Sandbox Code Playgroud)