win*_*ter 4 linux bash shell jq
我尝试使用 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}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为行:
echo ${data} | jq ${query}
Run Code Online (Sandbox Code Playgroud)
但如果我在 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
Run Code Online (Sandbox Code Playgroud)
我无法理解这里到底是什么问题,我只能认为在与 bash 一起使用时我需要以某种方式添加单引号。
例如,如果我使用单引号:
echo ${data} | jq \'${query}\'
Run Code Online (Sandbox Code Playgroud)
它给出了一个错误:
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
Run Code Online (Sandbox Code Playgroud)
'.[] 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}"
Run Code Online (Sandbox Code Playgroud)
{
"resource_name": "data2.something",
"resource_type": "Topic"
}
Run Code Online (Sandbox Code Playgroud)