带有单引号的jq bash脚本



我尝试使用bash运行以下脚本:

#!/bin/bash
myvar="data1"
data='[
{
"resource_name": "data1.something",
"resource_type": "Topic"
},
{
"resource_name": "data2.something",
"resource_type": "Topic"
}
]'
query=$(echo ".[] | select((.resource_type=="Topic") and (.resource_name | startswith("${myvar}") | not))")
echo ${data} | jq ${query}

由于线路原因,它不起作用:

echo ${data} | jq ${query}

但如果我在zsh中运行相同的脚本,它会起作用。并给我以下错误:

jq: error: Could not open file |: No such file or directory
jq: error: Could not open file select((.resource_type=="Topic"): No such file or directory
jq: error: Could not open file and: No such file or directory
jq: error: Could not open file (.resource_name: No such file or directory
jq: error: Could not open file |: No such file or directory
jq: error: Could not open file startswith("data1"): No such file or directory
jq: error: Could not open file |: No such file or directory
jq: error: Could not open file not)): No such file or directory

我无法理解这里到底是什么问题,我只能认为在与bash一起使用时,我需要添加单引号。

例如,如果我使用单引号:

echo ${data} | jq '${query}'

它给出一个错误:

jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:

"。[]jq:1编译错误

使用--arg选项将内容作为变量导入比将shell变量注入实际过滤器代码更可取。这也使您不用处理单引号或双引号。

#!/bin/bash
myvar="data1"
data='[
{
"resource_name": "data1.something",
"resource_type": "Topic"
},
{
"resource_name": "data2.something",
"resource_type": "Topic"
}
]'
query='.[] | select((.resource_type==$type) and (.resource_name | startswith($var) | not))'
echo "${data}" | jq --arg type "Topic" --arg var "${myvar}" "${query}"
{
"resource_name": "data2.something",
"resource_type": "Topic"
}

演示

相关内容

  • 没有找到相关文章

最新更新