0

I have these variables:

var1=ab
var2=cd
result=${var1}-text-${var2}
ab-text-cd=bingo

I have:

$ echo $result
ab-text-cd

I would like to have:

$ echo $result
bingo

Is it possible and how?

More info: Var1 and var2 are arguments given to script.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

0

Thanks to @Léa Gris. I didn't know about "indirect parameter expansion".

"If the first character of PARAMETER is an exclamation point, Bash uses the value of the variable formed from the rest of PARAMETER as the name of the variable."

Solution :

result2=$(echo ${!result1})
-1

You can use eval to achieve this. Be warned though, that using eval is almost always a bad idea, as it has glaring security issues (rooted in its design -- it is meant to execute everything passed to it) and even apart from that, all kinds of things might go wrong when a variable has an unexpected value.

result=${var1}-text-${var2}
eval ${var1}'_text_'${var2}=bingo
echo $ab_text_cd

Also, environment variables cannot have dashes (-) as part of the variable name, so I replaced them by underscores (_) for the example.

  • Hi ! Yeah I use underscores but when I was writing my question they wouldn't appear so I replaced them with dashes. Tried eval already but it wasn't what I was looking for. The "bingo" string is something I can "call" but not a string I chose because it depends on $var1 and $var2. They can have 5 different values each. – Black Desert Jan 24 '22 at 16:17
  • Since the question is tagged `bash`, there's really no need to even mention `eval`. – chepner Jan 24 '22 at 16:18
  • Also, there are no environment variables in this scenario. (You *can*, in fact, store names containing `-` in the environment of a process; those names just aren't exposed as ordinary *shell* variables.) – chepner Jan 24 '22 at 16:19