bash jq中的转义引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44516029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escape quotes in jq
提问by Mazzy
I've the following two bash lines
我有以下两条 bash 行
TMPFILE="$(mktemp)" || exit 1
< package.json jq '. + {"foo":'"${BOO}"'}' > "$TMPFILE"
but I get the following error:
但我收到以下错误:
jq: error: syntax error, unexpected '}' (Unix shell quoting issues?) at <top-level>, line 1:
. + {"foo":}
jq: 1 compile error
any idea how to escape properly that part by having the double quote there to mute the shellcheck error
任何想法如何通过在那里使用双引号来消除 shellcheck 错误来正确转义该部分
回答by Tom Fenech
Just use a variable and save yourself the hassle:
只需使用变量即可省去麻烦:
< package.json jq --arg b "$BOO" '. + { foo: $b }'
--arg b "$BOO"
creates a variable $b
that you can use inside jq
, without having to deal with quoting issues.
--arg b "$BOO"
创建一个$b
可以在 inside 使用的变量jq
,而无需处理引用问题。
That said, the reason that your attempt was failing was that you were missing some literal double quotes:
也就是说,您的尝试失败的原因是您缺少一些文字双引号:
< package.json jq '. + { foo: "'"$BOO"'" }'
The extra double quotes insideeach of the the single-quoted parts of the command are needed, as the other ones are consumed by the shell before the command string is passed to jq
.
额外的双引号内的每个命令的单引号的零件都需要,因为其他的人被shell命令字符串传递给之前消耗jq
。
This will still fail in the case that the shell variable contains any quotes, so the first approach is the preferred one.
如果 shell 变量包含任何引号,这仍然会失败,因此第一种方法是首选方法。