假设我有一个变量的名称存储在另一个变量中:
myvar=123 varname=myvar
现在,我想使用$varname变量来获取123.
有没有直接的方法呢?我发现没有这样的bash内置的名称查找,所以想出了这一点:
function var { v="\$$1"; eval "echo "$v; }
所以
var $varname # gives 123
最终看起来不太糟糕,但我想知道我是否错过了更明显的事情.提前致谢!
从
man page of bash:
${!varname}
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.