Search code examples
bashvariable-expansionparameter-expansion

Bash - Expanding a variable into another variable name


Let's say I have these variables:

VAR_A=resultA
VAR_B=resultB
X=A

I want to get the value of VAR_A or VAR_B based on the value of X.

This is working and gives resultA:

VAR="VAR_$X"
RESULT=${!VAR}

My question is, is there a one-liner for this?

Because indirection expansion doesn't seem to work if it is not the wole name of the variable which is expanded. I tried:

RESULT=${!VAR_$X}
RESULT=${!"VAR_$X"}

...and a lot of other combinations, but it always write "bad substitution"...


Solution

  • There doesn't appear to be a shorter way when using the bash 2 notation of ${!var}. For reference, the "new" bash 2 notation is value=${!string_name_var} and the "old" notation would be: eval value=\$$string_name_var.

    You could just use the old notation to make it work like you wanted:

    eval RESULT=\$"VAR_$X"
    

    Reference: https://www.tldp.org/LDP/abs/html/bashver2.html#BASH2REF