加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:32:16 所属栏目:安全 来源:网络整理
导读:假设我有一个变量的名称存储在另一个变量中: myvar=123varname=myvar 现在,我想使用$varname变量来获取123. 有没有直接的方法呢?我发现没有这样的bash内置的名称查找,所以想出了这一点: function var { v="$$1"; eval "echo "$v; } 所以 var $varname #
假设我有一个变量的名称存储在另一个变量中:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读