bash – 按名称间接查找shell变量

前端之家收集整理的这篇文章主要介绍了bash – 按名称间接查找shell变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一个变量的名称存储在另一个变量中:
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.

原文链接:https://www.f2er.com/bash/383844.html

猜你在找的Bash相关文章