The following command works fine if launched in a console:
/bin/lshw -quiet -json -C network|/bin/jq '.[1] | .logicalname'
Please, note the 1 in square brackets.
On my computer this command delivers:
root@t15:/home/hmb# /bin/lshw -quiet -json -C network|/bin/jq '.[1] | .logicalname'
"wlp9s0"
root@t15:/home/hmb#
When I tried to use this syntax within a bash script like this:
#!/bin/bash
# The next line works:
test1=$(/bin/lshw -quiet -json -C network|/bin/jq '.[1] | .logicalname')
/bin/echo "test1 = $test1"
i=1
# This line doesn't:
test2=$(/bin/lshw -quiet -json -C network|/bin/jq '.[$i] | .logicalname')
/bin/echo "test2 = $test2"
... things don't work as expected:
root@t15:/home/hmb/HPT/playground/hmbnetwatch# ./question.sh
test1 = "wlp9s0"
jq: error: $i is not defined at <top-level>, line 1:
.[$i] | .logicalname
jq: 1 compile error
test2 =
root@t15:/home/hmb/HPT/playground/hmbnetwatch#
I've tested all methods of escaping for the single quotes which occur in the jq command, but I wasn't able to use a script variable within these squared brackets.
I managed to find a way getting the needed information out of lshw by using an array, but out of curiosity and since I invested hours of trial and error without any success, I'd really like to know whether it is impossible to use a variable here or if there is a way.
It is said this is a duplicate of Passing bash variable to jq, but I don't think so. The question is why one should not inject a shell variable in the square brackets of jq
, which is not really answered elsewhere.