标签: bash
比方说,我有3个变量,A=1,B=2,C=3,最后是包含其中任何一个变量的最后一个变量(VAR=A)。是否可以根据VAR的内容调用A,B,C,如果没有,
A=1
B=2
C=3
VAR=A
赞echo "${$VAR}"?
echo "${$VAR}"
答案 0 :(得分:3)
是
eval echo \$$VAR
使用间接引用还有一种仅使用bash的方法:
echo ${!VAR}
答案 1 :(得分:3)
A=1 B=2 C=3 VAR=B echo ${!VAR}
输出:
2
文档(man bash):
If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. 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 indirection.