0

Please review the sample code setup for 3x3 2D associative Array matrix. and at the bottom I'm trying print all the elements from 2D bash associative array matrix... for e.g. all [args] keys... But I'm not getting what I needed... specific keys printed for e.g.: all [args] keys...

My bash version:

$ bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

What am I missing?

declare -A assocArr
echo "Intialize the Associative Array (assocArr):"
assocArr[0,pid]=12345; assocArr[0,args]='/path/to/app/args'; assocArr[0,uptime]='4-2:50:35'
assocArr[1,pid]=56789; assocArr[1,args]='/path/to/app/args'; assocArr[1,uptime]='1-2:50:42'
assocArr[2,pid]=54321; assocArr[2,args]='/path/to/app2/args'; assocArr[2,uptime]='3-2:30:23'

echo "print the Associative Array (assocArr) elements:"
echo "assocArr[0,pid] is ${assocArr[0,pid]} ; assocArr[0,args] is ${assocArr[0,args]} ; assocArr[0,uptime] is ${assocArr[0,uptime]}"
echo "assocArr[1,pid] is ${assocArr[1,pid]} ; assocArr[1,args] is ${assocArr[1,args]} ; assocArr[1,uptime] is ${assocArr[1,uptime]}"
echo "assocArr[2,pid] is ${assocArr[2,pid]} ; assocArr[2,args] is ${assocArr[2,args]} ; assocArr[2,uptime] is ${assocArr[2,uptime]}"


echo "random element printing"
echo "${assocArr[1,args]}"


echo "PRINT ALL ELEMENTS of a SPECIFIC [key] for e.g.: all [args]"
echo "{assocArr[@,args]} : 
       ${assocArr[@,args]}"

echo "{assocArr[@ args]} :
       ${assocArr[@ args]}"

echo "{assocArr[@][args]} :
       ${assocArr[@][args]}"
MaxGrand
  • 113
  • 1
  • 9
  • You're not saying what you get and what you think you should get. – Benjamin W. Aug 17 '17 at 21:20
  • 1
    Unless this is a new feature that for some reason I cannot find any info on, bash associative arrays are strictly 1-dimensional. You can have a key such as `0,pid`, but in this case it's a single key which is the string `"0,pid"`, not two separate keys `0` and `pid`. This is why it is recommended to quote keys when indexing associative arrays, e.g., `${array["$key"]}` – Mike Holt Aug 17 '17 at 21:23
  • You can simulate 2D arrays in bash, but you basically have to roll your own methods for doing so (e.g., `eval "declare -A array${id}"`, etc). I've done this before just on a lark, but I found it to be cumbersome and error-prone, and I wouldn't recommend it. – Mike Holt Aug 17 '17 at 21:25
  • My ignorance I guess; I latched onto the bash 2D Array idea from this another SO thread (https://stackoverflow.com/a/31276568/2288573). I now understand that Bash doesn't have a 2D array... and will have to devise something of my own – MaxGrand Aug 18 '17 at 01:18
  • @BenjaminW. just edited my question to improve it a bit... but I learnt already that Bash has no 2D Array feature... I ended up using simple associative arrays for each different values args, uptime etc; using PID as my key. – MaxGrand Aug 18 '17 at 14:22

0 Answers0