2

I tried the following 2D array set in bash:

$ a[0,0]=a0
$ a[1,0]=a1
$ echo ${a[0,0]}
a1

I expect to get a0, What I m missing?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    I'm not 100% sure of this but I think that `0,0` and `1,0` are being evaluated inside an arithmetic context, so you get the same result as `$((1,0))` and `$((0,0))` i.e. the first digit is evaluated and discarded, leaving you with `0` in both cases. I don't know where you got the idea that multi-dimensional arrays are supported in the first place though. – Tom Fenech Nov 24 '16 at 09:33
  • 2
    Bash **ONLY** provides one-dimensional indexed and associative array variables. Although there're some tricky ways to simulate multi-dimensional arrays, they are not a good solution. If you have the chance, you'd better move to other scripting languages such as Perl, Pyhton or even some versions of Ksh where multi-dimensional arrays are supported. – MarcM Nov 24 '16 at 09:38

2 Answers2

1

Bash has no support for multi-dimensional arrays, but you can simulate 2d arrays as discussed in this answer

Community
  • 1
  • 1
nradk
  • 680
  • 9
  • 19
0

The answer is to add

declare -A a
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 2
    Declaring a variable '-a' (array) doesn't provide multi-dimensional support. Bash ONLY supports one-dimensional arrays. Although there're some tricky ways to simulate multi-dimensional arrays, they are not a good solution. – MarcM Nov 24 '16 at 09:35
  • @MarcM it works for me – MOHAMED Nov 24 '16 at 09:39
  • @MOHAMED: this is not really a 2D array - it's just a hack which simulates 2D arrays using hashes - see [this answer](http://stackoverflow.com/a/16487733/253056) for a full explanation. – Paul R Dec 01 '16 at 17:21