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

bash – 使用shell命令的输出作为变量

发布时间:2020-12-15 16:59:36 所属栏目:安全 来源:网络整理
导读:参见英文答案 Create variable from string/nameonly parameter to extract data in bash?3个 我想使用echo命令的输出作为变量名.喜欢, var1="test"var2="script"echo ${$1} 如果$1是var1 echo应该打印测试. ${$1}抛出错误“错误替换” 你想要的是 variable
参见英文答案 > Create variable from string/nameonly parameter to extract data in bash?3个
我想使用echo命令的输出作为变量名.喜欢,
var1="test"
var2="script"
echo ${$1}

如果$1是var1 echo应该打印测试.

${$1}抛出错误“错误替换”

你想要的是 variable expansion(或间接扩展).您必须使用语法${!var}:
~$cat s.sh
var1="test"
var2="script"
echo ${!1}
~$./s.sh var1
test
~$./s.sh var2
script

来自man bash:

${parameter}

The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit,or when parameter is followed by a character which is not to be interpreted as part of its name.

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. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

(编辑:李大同)

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

    推荐文章
      热点阅读