OT: Bash arrays & indirection?

Patrick Lists fedora-list at puzzled.xs4all.nl
Thu Feb 16 15:41:19 UTC 2012


On 16-02-12 12:13, Ian Malone wrote:
> On 16 February 2012 08:43, Patrick Lists<fedora-list at puzzled.xs4all.nl>  wrote:
>> Hi,
>>
>> I am trying to do the following in bash:
>>
>> OPTIONS = ( alfa beta gamma )
>> SUBOPTIONS_alfa = ( alfa0 alfa1 )
>> count=0
>> SETCOUNT = ${#SUBOPTIONS_${OPTIONS[$count]}[@]}
>>
>> The SETCOUNT line gives a substitution error. I would like the
>> ${OPTIONS[$count]} to be substituted with alfa so SETCOUNT is:
>>
>> SETCOUNT = ${#SUBOPTIONS_alfa[@]} which should equal 2.
>>
>> Anyone have an idea how I can make this work? Quick and dirty is fine. I
>> have already been told that it should be done differently. I appreciate that
>> but right now I just want to make it work.
>>
>
> Pushing the limits of what can be done with bash, it's just about
> possible. As you mention this is the point you should consider
> translating to another language. Anyway...
>
> http://stackoverflow.com/questions/4582137/bash-indirect-array-addressing

I missed that one. Good link.

> Also N.B. shouldn't be any spaces around those equals signs in your example.
>
> OPTIONS=( alfa beta gamma )
> SUBOPTIONS_alfa=( alfa0 alfa1 )
> SUBOPTIONS_beta=( beta_1 )
> SUBOPTIONS_gamma = ( gamma_1 gamma_2 gamma_3 )
> count=0
> #then...
> for count in {0..2} ; do
> nameSUBOPTS=SUBOPTIONS_${OPTIONS[$count]}[@]
> tmpARR=(${!nameSUBOPTS}) #You need tmpARR, because the '#' expansion
> wont work with '!'
> SETCOUNT=${#tmpARR[@]}
> echo ${OPTIONS[$count]}:$SETCOUNT
> done

Thanks! I will try it out. It looks more sane that what I found myself 
which apparently is challenging the bash gods to unleash their wrath if 
I use it:

eval SETCOUNT=\${#SUBOPTIONS_${OPTIONS[$count]}[@]}

> Finally, it's spelt 'alpha' ;)

Heh spelt or spelled? :) Actually I was thinking about the cars but 
thought alfa bentley corvette was lame so went with alfa beta and gamma.

Thank you for helping out.

Cheers,
Patrick


More information about the users mailing list