1

I'm trying to use a variable as part of another variable's name.

For example, I have some variables in a CONFIG_ scope.

echo $CONFIG_systema_value > "testconfig"
echo $CONFIG_systemb_value > "testconfig2"

and then I have a "deciding" variable like WANTEDSYSTEM

echo $WANTEDSYSTEM > "systema"

I need to be able to "dynamically" switch the config depending on the wantedsystem variable.

My initial attempts I tried something like this echo $CONFIG_$WANTEDSYSTEM_value which I would like to have output testconfig as if I was asking it to echo $CONFIG_systema_value

1 Answer 1

5

You can use the ${!name} syntax to indirectly reference a variable, like this:

CONFIG_systema_value=foo
CONFIG_systemb_value=bar
WANTEDSYSTEM=systema

target_var_name="CONFIG_${WANTEDSYSTEM}_value"
echo ${!target_var_name}

(Note that this is bash-specific syntax, but it sounds like that's what you're looking for.)

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't it any trick with eval to make it in one line with echo?
Sure, you could write something like eval echo "\$CONFIG_${WANTEDSYSTEM}_value", but I avoid eval when possible because if you're not careful what you pass to it it can have unintended side effects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.