将bash shell变量传递给jq过滤器

时间:2018-10-23 23:45:01

标签: bash shell jq

试图将bash shell变量传递到jq过滤器中

JSON:

{
"server1": {
"port": 3333,
"name": "foo",
"timesincelast": 248054
},
"server2": {
"port": 4444,
"name": "bar",
"timesincelast": 248054
  }
  }

试图执行的Bash命令:

 servername='server1'
 jq --arg servername "$servername" '.$servername .port'

但是出现错误

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

但是直接替换有效

jq '.server1 .port'

1 个答案:

答案 0 :(得分:1)

您可以写:

.[$servername] | .port

或简单地:

.[$servername].port