按名称查找shell变量,间接地 [英] Lookup shell variables by name, indirectly
问题描述
让我们说我有一个变量的名字保存在另外一个变量:
MYVAR = 123
VARNAME = MYVAR
现在,我想只要使用$ varname的变量获得123。
是否有一个直接的方法?我发现内置由名称查找没有这样的庆典,所以想出了这个:
函数VAR {V =\\ $$ 1; EVAL回声$ V; }
所以
变量$#VARNAME 123提供
看起来并不太坏到底,但我想知道如果我错过了一些比较明显的。在此先感谢!
从的庆典手册页:
$ {!VARNAME}
如果参数的第一个字符是一个感叹号,水平
可变间接介绍。 bash使用从参数作为变量的名称的其余部分形成的变量的值;
然后这个变量被扩展并且该值是在的其余部分中使用
取代,而不是参数本身的值。这是
被称为间接扩张。
块引用>Let's say I have a variable's name stored in another variable:
myvar=123 varname=myvar
now, I'd like to get 123 by just using $varname variable. Is there a direct way for that? I found no such bash builtin for lookup by name, so came up with this:
function var { v="\$$1"; eval "echo "$v; }
so
var $varname # gives 123
Which doesn't look too bad in the end, but I'm wondering if I missed something more obvious. Thanks in advance!
解决方案From the 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.
这篇关于按名称查找shell变量,间接地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!