I had the following piece of az cli output in plain text:
echo $raw_containers_string [ { "name": "123" }, { "name": "vbm-container" } ] After some text refinement, I have a string returned containing this (zsh):
echo $raw_containers_string | grep name | cut -d ":" -f2 | tr '\n' " " "123" "vbm-container" % (It also has a % symbol at the end, but that's expected)
I now need to create an array of these 2 strings (123 and vbm-container) to iterate through it.
declare -a arr=($(echo $raw_containers_string | grep name | cut -d ":" -f2 | tr '\n' " "))- returns
"123" "vb -co t i r"
- returns
arr=($(echo $raw_containers_string | grep name | cut -d ":" -f2 | tr '\n' " "))- returns
"123" "vb -co t i r"
- returns
These are indices of an array (if it matters):
➜ bash-az-list-blobs git:(master) ✗ echo $myvar[0] ➜ bash-az-list-blobs git:(master) ✗ echo $myvar[1] "123" "vb ➜ bash-az-list-blobs git:(master) ✗ echo $myvar[2] -co ➜ bash-az-list-blobs git:(master) ✗ echo $myvar[3] t ➜ bash-az-list-blobs git:(master) ✗ echo $myvar[4] i ➜ bash-az-list-blobs git:(master) ✗ echo $myvar[5] ➜ bash-az-list-blobs git:(master) ✗ echo $myvar[6] r" Questions
- I want to understand why the behaviour between printing it to the terminal and assigning it to a variable is different.
- I would also like to know how I assign my refined to an array in zsh, so that
echo arrreturns a 2-elements iterable array.
UPD (08-16)
Using jq does filter JSON successfully
echo "$raw_containers_string" | jq -r '.[].name' 123 vbm-container The problem is to pack these values into an array (this was exactly the purpose of this thread):
declare -a arr=$(echo "$raw_containers_string" | jq -r '.[].name') echo $arr 123 vbm-container echo $arr[0] 123 vbm-container[0] echo $arr[1] 123 vbm-container[1] Why accessing the first element of my array just add index "[0]" to an output?
echo "$raw_containers_string" | jq -r '.[].name' → 123 vbm-container declare -a containers_array=($(echo "$raw_containers_string" | jq -r '.[].name|@sh' | tr '\n' " ")) → "123" eval "containers_array=($(echo "$raw_containers_string" | jq -r '.[].name|@sh'))" → 123 eval "containers_array=($(echo "$raw_containers_string" | jq '.[].name|@sh'))" → '123' echo $IFS →