-2

As bash does not support multi-dimensional arrays, how can I fake it so I could access it like this:

#declare
array["foo"] = "bar"

#print
echo array["foo"] //how to display declared 'bar' here?

So the question is: what I need to do, to print out the bar when accessing array["foo"]?

Lucas
  • 3,517
  • 13
  • 46
  • 75

1 Answers1

1

You simply need to use associative arrays:

declare -A array=()

#declare
array["foo"]="bar"

#print
echo "${array["foo"]}"

And you can fake multi-dimensional arrays with it like

i=1
j=2
array[$i,$j]=1234
echo "${array[$i,$j]}"
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • It only works for one element: `declare -a array=(["moo"]="cow" ["john"]="doe")` : `echo "${array["moo"]}" //returns doe[!] which is wrong`, `echo "${array["john"]}" //returns doe aswell which is fine` – Lucas Sep 13 '13 at 11:35
  • When I do only one echo like `echo ${array["moo"]}"` it works fine, but problem appears when I want to print more than one array element. – Lucas Sep 13 '13 at 11:36
  • @Lucas Make sure you declare your array as associative with `declare -A` not `-a`. – konsolebox Sep 13 '13 at 11:37
  • Thats strange - I have used `-a` parameter because when I do `-A` this is what I get: `declare: -A: invalid option` `declare: usage: declare [-afFirtx] [-p] [name[=value] ...]` I am using the following bash: `#!/usr/local/bin/bash` – Lucas Sep 13 '13 at 11:57
  • I think that `declare -A` is in 4.0 and later versions of bash. I'm running the `3.2.48`. – Lucas Sep 13 '13 at 12:07
  • @Lucas Yes it's only available in 4.0. The latest version of bash is 4.2 and I was expecting that most systems has already upgraded to 4.0 at least. – konsolebox Sep 13 '13 at 12:12
  • OVH's dedicated server running on latest FreeBSD has installed the default version of `3.2.48`. I'd better upgrade this oldie. Thanks for your help! – Lucas Sep 13 '13 at 12:15
  • You're welcome. I suggest going for 4.2.45. It seems the most stable over all its previous versions. – konsolebox Sep 13 '13 at 12:17