3

If I have

arr[0,0]=0;
arr[0,1]=1;

And I try

echo ${#arr[0,@]}

I got

bash: 0,@: syntax error: operand expected (error token is "@")

What is the correct way to get the size of the second dimension or arr?

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • 1
    Not string keys; the index is evaluated in an arithmetic context, in which the comma operator is supported – chepner Jul 07 '15 at 16:30
  • Given the error this is arithmetic context. Without that this could be an associative array in which case anubhava would be correct. – Etan Reisner Jul 07 '15 at 16:31

2 Answers2

3

Multi-dimensional arrays are not supported in BASH.
Nevertheless, you could simulate them using various techniques.

The following definitions are the same:

  • arr[1,10]=anything
  • arr["1,10"]=anything

Both are evaluated to arr[10]=anything (thanks chepner):

echo ${arr[10]}
anything
Community
  • 1
  • 1
Eugeniu Rosca
  • 5,177
  • 16
  • 45
  • Then why is it legit to define `arr[0,0]=0`? – OneZero Jul 07 '15 at 16:28
  • 5
    Because `0,0` is a legitimate arithmetic expression that evaluates to 0. (The comma operator returns the value of the second expression.) – chepner Jul 07 '15 at 16:30
  • 1
    @OneZero And for associative arrays it means string key `"0,0"`. – Etan Reisner Jul 07 '15 at 16:30
  • While I recognize there are ways to simulate them, how do I deal with the size problem then? If `0,0` is interpreted as a whole string, does it mean there's no way I can get the size of a second dimension? – OneZero Jul 07 '15 at 16:35
  • @OneZero If you are using string indices to simulate them? Correct, you can't do it without counting (though that could be as simple as key expansion and parameter expansion I think). – Etan Reisner Jul 07 '15 at 16:38
  • 3
    @OneZero: If I needed 2d arrays, I would switch from bash to a language that supports them natively. – Eugeniu Rosca Jul 07 '15 at 16:41
  • @chepner: your precious note put in the answer. thanks. – Eugeniu Rosca Jul 07 '15 at 16:49
0

Bash doesn't have multi-dimensional array. What you are trying to do, won't even simulate a multi-dimensional array unless you have declared the arr variable as an associative array. Check out the following test:

#!/bin/bash
arr[0,0]=0
arr[0,1]=1
arr[1,0]=2
arr[1,1]=3
echo "${arr[0,0]} ${arr[0,1]}" # will print 2 3 not 0 1
unset arr
declare -A arr
arr[0,0]=0
arr[0,1]=1
arr[1,0]=2
arr[1,1]=3
echo "${arr[0,0]} ${arr[0,1]}" # will print 0 1

And you can only get the size as a whole with ${arr[@]}

Jahid
  • 21,542
  • 10
  • 90
  • 108