假设我们有:
echo $A
abc
echo $B
def
echo $abcdef
yesyes
如何使用 A 和 B 得到“yesyes”?我正在尝试类似的事情:
${$A$B}
$`echo "$A"$B`
但失败了。有什么建议吗?
答案1
如果您使用的是 Bash shell,那么只要您引入一个可以使用的中间变量间接:
$ echo $A
abc
$ echo $B
def
$ echo $abcdef
yesyes
然后
$ AB=$A$B
$ echo "${!AB}"
yesyes
Bash 手册 ( ) 的 **参数扩展* 部分描述了变量间接寻址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.
答案2
你可以这样做:
$ eval "echo \$$(echo ${A}${B})"
yesyes
以上是一般形式,eval "echo \$$(echo ...)
。上面将变量转换${A}${B}
为字符串abcdef
,然后将其评估为字符串echo \$abcdef
。
如果你把它取下来,eval
你可以看到中间形式:
$ echo \$$(echo ${A}${B})
$abcdef
然后eval
扩展变量$abcdef
。