I have a json store in jsonFile
{ "key1": "aaaa bbbbb", "key2": "cccc ddddd" }
I have code in mycode.sh
:
#!/bin/bash value=($(jq -r '.key1' jsonFile)) echo "$value"
After I run ./mycode.sh
the result is aaaa
but if I just run jq -r '.key1' jsonFile
the result is aaaa bbbbb
Could anyone help me?
A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. Output: This simple example initializes a string and prints the value using the “$” operator.
With that line of code
value=($(jq -r '.key1' jsonFile))
you are assigning both values to an array. Note the outer parantheses ()
around the command. Thus you can access the values individually or echo the content of the entire array.
$ echo "${value[@]}" aaaa bbbb $ echo "${value[0]}" aaaa $ echo "${value[1]}" bbbb
Since you echoed $value
without specifying which value you want to get you only get the first value of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With