1

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"...

scandel
  • 1,692
  • 3
  • 20
  • 39
  • Possible duplicate of [Bash expand variable in a variable](https://stackoverflow.com/questions/14049057/bash-expand-variable-in-a-variable) – Corentin Limier Jul 15 '19 at 13:07
  • @CorentinLimier no, I'm sorry, this is not the same question, because the X variable is included into another variable as a string, and indirection expansion doesn't work in that case. That is the whole point of my question! – scandel Jul 15 '19 at 13:25

3 Answers3

4

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

Leon S.
  • 3,337
  • 1
  • 19
  • 16
1

You'd be better off using an associative array, at least on recent versions of Bash:

declare -A var=(
    [A]=resultA
    [B]=resultB
)
x=A
result="${var[$x]}"
echo "$result"  # -> resultA
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    I know this would be a better option, but I'm in a context where it is not possible (env vars declared in Gitlab-CI - no arrays allowed). – scandel Jul 16 '19 at 08:29
0

This should work.

RESULT=$(eval echo \$VAR_$X)

The \ in front of the $ makes it be treated literally.

j23
  • 3,139
  • 1
  • 6
  • 13