Passing bash shell variable to jq filter

2020-03-31 09:20发布

问题:

Trying to pass a bash shell variable into a jq filter

JSON:

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

Bash command trying to execute:

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

But getting an error

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

But direct substitution works

jq '.server1 .port'

回答1:

You could write:

.[$servername] | .port

or simply:

.[$servername].port


标签: bash shell jq