将heredoc声明压缩为bash中的一行? [英] Compress heredoc declaration to one line in bash?

查看:91
本文介绍了将heredoc声明压缩为bash中的一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法可以在bash脚本中声明JSON字符串:

I have this which works to declare a JSON string in a bash script:

   local my_var="foobar"
   local json=`cat <<EOF
  {"quicklock":"${my_var}"}
EOF`

上面的Heredoc可以工作,但是我似乎无法以其他任何方式对其进行格式化,它的字面看起来必须完全像大声笑一样.

The above heredoc works, but I can't seem to format it any other way, it literally has to look exactly like that lol.

有没有办法使命令在一行上,像这样:

Is there any way to get the command to be on one line, something like this:

   local json=`cat <<EOF{"quicklock":"${my_var}"}EOF`

那会好得多,但似乎并没有采取,显然是因为我猜这不是EOF的工作原理.

that would be so much nicer, but doesn't seem to take, obviously simply because that's not how EOF works I guess lol.

我正在寻找一种在文件中声明JSON的简便方法:

  1. 不需要大量的转义字符.
  2. 这允许对变量进行动态插值.

注意:我要使用的实际JSON具有多个动态变量,其中包含许多键/值对.请推断.

Note: The actual JSON I want to use has multiple dynamic variables with many key/value pairs. Please extrapolate.

推荐答案

为什么不使用 jq ?在管理字符串插值方面非常擅长,而且它可以简化您的结构.

why not use jq? It's pretty good at managing string interpolation and it lints your structure.

$ echo '{}' >> foo.json
$ local myvar="assigned-var"
$ jq --arg ql $myvar '.quicklock=$ql' foo.json

在调用jq的另一端出现的文本然后可以cat到文件中或您想执行的任何操作.文字看起来像这样:

the text that comes out on the other end of that call to jq can then be cat into a file or whatever you wanna do. text would look something like this:

{"quicklock"="assigned-var"}

这篇关于将heredoc声明压缩为bash中的一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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