Multidimensional arrays

Hi Experts,

I'm a newbie.....multidimensional arrays in shell scripts is possible???
If so, can anyone guide me with an example.....and also can anyone tell me, how we can create a table like ouput format in shell script....the output should look like this one:

1 2 3 4 5 6
6 5 4 3 2 1
1 2 3 1 2 1
2 2 3 3 4 5
7 8 9 0 4 2
matrix/table with rows and columns kind of output is that possible......kindly explain me with some examples....

Thanks for ur help,
Kriti........:):slight_smile:

Depends on what "shell". Even in ancient of days Bourne shell (something you'll still find on many Solaris hosts), you can always think of an array as:

varname_${index1}_${index2}

If you just had to. In other words, you can use variable values to create unique variable names... and thus get an array effect.

bash and ksh have arrays, new editions of korn shell (and bash as well) support single dimension indexed as well as associative arrays. You can exploit associative arrays to do quasi-multi dimensional array indexing using a similar technique to what I described for bourne shell... e.g varname["${index1} ${index2}"]

So assignment isn't necessarily hard in the bourne shell case... but evaluating requires an extra level of evaluation to be performed, so you have to do some extra escaping.

index1=9
index2=12
eval varname_${index1}_${index2}=\"my value\"

eval val=\"\$varname_${index1}_${index2}\"

Korn/bash won't have this extra eval requirement. So you can just do (in bash):

declare -A varname
index1=1
index2=2
varname["${index1} ${index2}"]='my value'

val=${varname["${index1} ${index2}"]}

(I realize I'm not being consistent... the underscore is a requirement in the bourne shell case, since it's just named variables really, and I'm using space as the separator between the indices in the korn/bash associative array case)

Hope that helps get you on your way!!

I find using comma as the seperator for the bash associative arrays (BTW you need bash version 4.0 or later) needed tends to read a lot better:

#!/bin/bash
delcare -A matrix
matrix[1,2]=2
matrix[2,2]=5
echo ${matrix[2,2]}  # outputs 5

Thanks for ur reply.....

Kindly anyone suggest me, where i can start to learn more about arrays and multidimensional arrays.....am a newbie.......so pls help me out.......

Hello!

Your question(s) could easily be answered by searching the Internet with Google. Google is your friend :smiley:

Per forum rules, and the benefit of all users, please search the network and the forums before posting a question.

You can easily search the forums using our internal Google search engine or our advanced internal search engine. You can also search our huge UNIX and Linux database by user generated tags or search the database for unanswered questions and provide an answer.

Thank you.

The UNIX and Linux Forums