Duncan_McCloud
Duncan_McCloud

Reputation: 553

Ksh nested substitution

I have the following configuration file:

export PROFILE_ACTIVE=0 

export PROFILE_SCSADP01[0]="0 84"
export PROFILE_SCSADP04[0]="85 170"
export PROFILE_SCSADP05[0]="171 255"

export PROFILE_SCSADP01[1]="-1 -1"
export PROFILE_SCSADP04[1]="85 170|0 42"
export PROFILE_SCSADP05[1]="171 255|43 84"

I would like to access these variable using substitution in a ksh script:

I can easily access each variable using this syntax, which is working:

result=${PROFILE_SCSADP01[${PROFILE_ACTIVE}]}

However I need the bold part to be variable, not fixed.

I have tired this syntax:

Temp="PROFILE_SCSADP01"
result=${$Temp[${PROFILE_ACTIVE}]}

However I always get a bad substituion error. I have tried to look for workaround, but cannot find any working,

Upvotes: 0

Views: 740

Answers (1)

Josh Jolly
Josh Jolly

Reputation: 11796

ksh has the typeset -n command for this (see here), which I think would be the preferred solution:

typeset -n tmp="PROFILE_SCSADP01"
result=${tmp[${PROFILE_ACTIVE}]}

You could also useeval (be careful) for this:

tmp="PROFILE_SCSADP01"
result=$(eval echo \${$tmp[${PROFILE_ACTIVE}]})

eval parses the command once before it is run, so after the eval completes, the resulting command looks like this:

result=$(echo ${PROFILE_SCSADP01[0]})

Upvotes: 1

Related Questions