0

So I have been looking and looking online to figure out how to make a two dimensional array. Like I kinda understand a one line linear array. But when I look online all I see is a bunch of code that I don't even understand what each component of the code does. Thanks for whoever answers.

Can you please explain important parts of the code to me and there function.

2
  • 1
    Have you seen this post: stackoverflow.com/questions/11233825/… Commented Feb 27, 2013 at 0:51
  • @paddy All this says is to use python. Also bash can now do multidim with bash 4.0 Commented Feb 27, 2013 at 0:54

2 Answers 2

3

A multidimensional array is just a special case of an associative array in bash 4:

# Make myarray an associative array
declare -A myarray 

# Assign some random value
myarray[3,7]="foo"

# Access it through variables
x=3 y=7
echo "${myarray[$x,$y]}"

It works because "3,7" is just a string like any other. It could just as well have been "warthog" or "ThreeCommaSeven". As long as everything else in your code turns the indices 3 and 7 into the string "3,7", it'll work just like a multidimensional array.

Sign up to request clarification or add additional context in comments.

4 Comments

would't this still be linear though @that other guy
so what would be the output of this 'foo'? So how does that make it 2d ? Can you give a small ex with output please. Thanks sorry for my no understanding @that other guy
This is as good a way as any to implement a multidimensional array. If what you are really looking for is an array-of-arrays, where something like ${x[2]} is another array, then bash is not the language for you. It's possible, but it quickly gets ugly, as you have to fake it with indirect parameter expansion and/or eval.
@Lifetake This is a complete example, and it outputs foo. It's 2D because you index it with two integer variables, just like a 2D array in any other language. It's not linear because no bash arrays are ever linear, they're always sparse.
2

If you want to list the elements without knowing in advance their number, a very handy solution:

a=()
a+=( Mexico,2000 )
a+=( Canada,3000 )

for row in ${a[@]};
do
    echo place: ${row%%,*} airplanes: ${row##*,}
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.