1

Would appreciate some advice, I am querying a IOT devices api which returns a JSON file however, order of the data is not always in sequentially output.

I have successfully extracted the value number from the json using bash and concatenated and store this into a variable. In order to sort and store the data I want to be able to create a variable based on the value of the concatenated variable. I'm using jq to query the json and array index to query the different objects in JSON and created $id:

did=myvar$id
echo $did
myvar10

This is where i'm stuck now, i want to be able to create a new variable from the value stored in $did

As an example,

  • if i echo $did and this returns myvar10, i require a new variable created to be called $myvar10.
  • If i echo $dis and this returns myvar8, i require a new variable created to be called $myvar8.

please can someone help push me in the right direction?

TIA

Samosa
  • 81
  • myvar10=$did but you can't be asking something this basic since you already showed you know this from your example code, if this isn't what you need, then add more to your post to clarify. – Lizardx Oct 20 '22 at 23:54
  • Perhaps you're asking about variable indirection? see for example Bash: Echo a variable whose name is the value of another variable – steeldriver Oct 21 '22 at 00:11
  • 2
    Could you use an associative array to store information using variable keys? declare -A myvararray ; id=10 ; did="myvar$id" ; myvararray[$did]="something" ; echo "${myvararray["myvar10"]}" (outputs "something"). – frabjous Oct 21 '22 at 00:12
  • 2
    Creating variable names on the fly isn't a good idea. There are a number of better alternatives such as using the variable "number", such as 10 from myvar10, or even the name itself, to index into an array of values – Chris Davies Oct 21 '22 at 09:37
  • 3
    Rather than getting help with the current query, it might be better to ask for help with what it is you actually want to do, which seems to be sorting (and splitting?) the contents of a JSON file (which you don't show). Parsing the output of jq in bash, creating variables with odd names taken from user-supplied data is not the way to go. jq can sort, extract, and do all sorts of operations on JSON documents. – Kusalananda Oct 21 '22 at 09:41

0 Answers0