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

2
  • Possible duplicate of Bash expand variable in a variable Commented Jul 15, 2019 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! Commented Jul 15, 2019 at 13:25

3 Answers 3

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

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

Comments

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

1 Comment

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).
0

This should work.

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

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

1 Comment

Even shorter eval RESULT=\$VAR_$X

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.