Suppose we have:
echo $A
abc
echo $B
def
echo $abcdef
yesyes
How do I get "yesyes" using A and B? I was trying something like:
${$A$B}
$`echo "$A"$B`
but failed. Any advise?
Suppose we have:
echo $A
abc
echo $B
def
echo $abcdef
yesyes
How do I get "yesyes" using A and B? I was trying something like:
${$A$B}
$`echo "$A"$B`
but failed. Any advise?
If you are using the Bash shell, then provided you introduce an intermediate variable you can use indirection:
$ echo $A
abc
$ echo $B
def
$ echo $abcdef
yesyes
then
$ AB=$A$B
$ echo "${!AB}"
yesyes
Variable indirection is described in the **Parameter Expansion* section of the Bash manual (man bash
):
If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirec‐ tion.
You can do it like so:
$ eval "echo \$$(echo ${A}${B})"
yesyes
The above is of the general form, eval "echo \$$(echo ...)
. The above converts the variables, ${A}${B}
into the string abcdef
, and then eval's it as echo \$abcdef
.
If you take the eval
off you can see the intermediate form:
$ echo \$$(echo ${A}${B})
$abcdef
The eval
is then expanding the variable, $abcdef
.
eval echo \$"$A$B"
for example)?
– steeldriver
Jul 03 '18 at 02:12
eval "echo \$"${A}${B}""
works, but when I explain this to ppl at work etc, they're more confused by this, vs. the extra echo'ing, in my experience. It also allows for the pieces to be taken out and executed independently to see what's happening, IMO. But yours is more concise.
– slm
Jul 03 '18 at 02:16