Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use jq syntax within a bash script?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Thank you very much!

>Solution :

No, don’t inject shell variables into your jq filter! Rather use options provided by jq to introduce them as variables inside jq. In your case, when using a variable that holds a number, --argjson will do:

i=1
test2=$(/bin/lshw -quiet -json -C network|/bin/jq --argjson i $i '.[$i] | .logicalname')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading