scandel
scandel

Reputation: 1832

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

Upvotes: 1

Views: 297

Answers (3)

wjandrea
wjandrea

Reputation: 33159

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

Upvotes: 1

j23
j23

Reputation: 3530

This should work.

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

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

Upvotes: 0

Leon S.
Leon S.

Reputation: 3687

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

Upvotes: 4

Related Questions