3

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?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

2 Answers2

3

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.
steeldriver
  • 81,074
  • Thank you! Didn't know "exclamation mark" can be used this way. Can you help provide some more introduction of the use of ! in cases like this? a link or a manual will be great. – user297997 Jul 03 '18 at 00:41
  • @user297997 I have added an extract from the documentation – steeldriver Jul 03 '18 at 00:51
0

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.

References

slm
  • 369,824
  • worked perfectly! – user297997 Jul 03 '18 at 00:11
  • What does the additional echo + command substitution do for you here (as opposed to eval echo \$"$A$B" for example)? – steeldriver Jul 03 '18 at 02:12
  • @steeldriver - nothing beyond showing ppl how to more mechanically put these things together. 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