NavigationtagsRecent comments
User login |
Emulating two-dimensional (or even multi-dimensional) arrays in bashEver needed to use arrays of two or more dimensions but got stuck on Bash limited array support which provides only 1 dimension? There is a trick that let's you dynamically create variable names. Using this, you can emulate additional dimensions. Here's a simple example for an array with 2 dimensions:
Thanks to the guys from #bash on freenode for their help and their excellent bash faq Trackback URL for this post:http://dieter.plaetinck.be/trackback/30
Submitted by Dieter_be on Sun, 08/26/2007 - 12:49. categories [ ]
|
Scope issues
Beware, when you use declare then your variables become scoped! (unlike "normal" variables in bash)
does not work for me. I
does not work for me.
I think what you mean is more something like that:
venus tools # var=(my_array5-10 a) ; echo ${!var[*]}
0 1
venus tools # var=(my_array5-10 a) ; var[33]="lala" ; echo ${!var[*]}
0 1 33
venus tools #
this is possible since bash-3.0 i think.
cheers
var="my_array25-10"; declare
var="my_array25-10"; declare $var="value"
-bash: declare: `my_array25-10=value': not a valid identifier
bash 3.1 ... what now?
What if you placed the
What if you placed the value in the array and just referenced it ?
Like if you had four values to save reserve array[0-4] for it then array[5-8] for next value ?
Or create two, three or four + arrays ?
Anonymous, if I understand
Anonymous, if I understand correctly you basically mean to store entries as foo[k*i + j] where k<=max(j). this works, sure. Though it is imho a bit less flexible.
Using multiple array variables, and considering the variable name one of the dimensions, that seems like a good alternative approach indeed.
not a valid identifier
If you get "not a valid identifier" this is because of the '-' character which is not allowed in variable names (anymore?). With an underscore it works ('_')
Multidimensional Array Simulation
This is a code snippet of some syntax checking I am doing. I am not including all the code that needs to be written to get this to work. If you have one dimension of the array that needs to represent the disk group and the second dimension to be the slices in each of the disk group you could do something similar to this:
Note that the eval and echo statements and the double eval require some pretty tricky syntax in korn shell. there may be better ways to do this, for sure. But initially it works. If I run the code, the result is "root"
(provided none of the syntax gets munged by the web posting I do.) :)
Post new comment