0

Here is the code I have question on

#!/bin/bash

declare -a data81

for ((i=1; i<=3; i++))
do
    for ((j=1; j<=2; j++))
    do
        data81[$i, $j]=$i
        printf "%4s" ${data81[$i, $j]}
        printf "%4s\n" ${data81[1, 1]}
    done
    echo
done

The output is the following:

   1   1
   1   1

   2   2
   2   2

   3   3
   3   3

which is not what I wanted, because I used printf "%4s\n" ${data81[1, 1]}, so the second column should be the same.

user6948979
  • 65
  • 2
  • 9
  • 4
    There are no two-dimensional arrays in Bash. The code you have does not do what you think it does. – Fred Feb 25 '17 at 17:38
  • 1
    You can simulate multi-dimensional array using associative arrays. See this post: http://stackoverflow.com/questions/11233825/multi-dimensional-arrays-in-bash – codeforester Feb 25 '17 at 17:40
  • 1
    Possible duplicate of [Multi-dimensional arrays in Bash](http://stackoverflow.com/questions/11233825/multi-dimensional-arrays-in-bash) – codeforester Feb 25 '17 at 17:42
  • The index is evaluated in an arithmetic context, where `$i, $j` evaluates to `$i`. – chepner Feb 25 '17 at 17:42
  • 2
    If you need to work with two-dimensional arrays, pick a different language. – chepner Feb 25 '17 at 17:42

2 Answers2

0

Change this line :

declare -a data81

To this :

declare -A data81

This does not create a multi-dimensional array, but rather an associative array. The index is a string that acts as a key to a dictionary-type data structure. Be careful how you build the index, it must have the exact same structure every time you access an element.

Fred
  • 6,590
  • 9
  • 20
  • Fred: I changed -a to -A, but my Mac complained that ` line 3: declare: -A: invalid optiondeclare: usage: declare [-afFirtx] [-p] [name[=value] ...]` – user6948979 Feb 25 '17 at 17:59
  • MacOS Bash is stuck at an older version that did not support associative arrays.. – Fred Feb 25 '17 at 18:00
  • I am not used to MacOS. It is very likely you can compile a recent version (but I cannot tell you how to do it), as the reason Apple has not updated is due, I think, to not liking the licence under which Bash 4 is published, and not to a technical limitation. Maybe there is a way to get it pre-compiled, I really do not know. – Fred Feb 25 '17 at 18:31
  • If you have HomeBrew, you can use this command: `brew install bash` – codeforester Feb 25 '17 at 18:32
  • Its also easy to download the source and build it yourself. – cdarke Feb 25 '17 at 18:36
0

You may try this way.

#!/bin/bash

declare -a data81

for ((i=1; i<=3; i++))
do
    for ((j=1; j<=2; j++))
    do
        data81[$i$j]=$i
        printf "%4s" ${data81[$i$j]}
        printf "%4s\n" ${data81[11]}
    done
    echo
done
Shiping
  • 1,203
  • 2
  • 11
  • 21