我嘗試使用 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}
它不起作用,因為 line :
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 編譯錯誤
uj5u.com熱心網友回復:
使用--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"
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440879.html
