按名称间接查找 shell 变量 [英] Lookup shell variables by name, indirectly
问题描述
假设我有一个变量的名称存储在另一个变量中:
myvar=123变量名=我的变量
现在,我想通过使用 $varname
变量来获得 123
.有没有直接的方法?我发现没有这样的 bash 内置用于按名称查找,所以想出了这个:
function var { v=$$1";评估回声"$v;}
所以
var $varname # 给出 123
最后看起来还不错,但我想知道我是否遗漏了一些更明显的东西.
来自 bash 手册页:
${!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.
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屋!