Variable within variable expansion

Hi,

I have been trying to get variable within variable expansion to work but have not been able to succeed. It seems that the two suggestions I am seeing are using 'eval' and using the built in bash capability of "${!test}". Here is a snippet of what I"m trying to accomplish:

#!/bin/bash
b2b_qa_site=1234
b2c_qa_site=4321
b2b_prd_site=5678
b2c_prd_site=8765

grp=`echo "${1: -2:1}"`
env=`echo "${1: -3:1}"`


if [[ $env -eq 4 ]]; then

        env=prd

else

        env=qa

fi

if [[ $grp -eq 0 ]]; then

        grp=b2b

else

        grp=b2c

fi

test=${grp}_${env}_site
eval echo \$test

This would be used as:

# ./script box400

And ideally receive:

5678

Can anyone shed some light on what I am doing wrong here? I appreciate any guidance.

Thanks,
HB

You were close. Try either

eval echo \$$test
5678

or

echo ${!test}
5678

Your approach might not be the best one. Ever thought about e.g. (associative) arrays?

1 Like

@RudiC, much appreciated.

Your comment on this not being the best approach is not surprising ;-)... I continue to try and improve my efforts but due to my skill level, usually start with functionality. I will investigate your suggestion of associative arrays.

Any high level example of how to better do what I'm trying with associative arrays?

Thanks again..

HB