使用变量来引用Bash中的另一个变量
发布时间:2020-12-16 01:40:34  所属栏目:安全  来源:网络整理 
            导读:x=1c1=string1c2=string2c3=string3echo $c1string1 我想通过使用类似的东西使输出为string1: echo $(c($x)) 所以稍后在脚本中我可以增加x的值并输出string1,然后输出string2和string3. 谁能指出我正确的方向? 解决方法 请参阅Bash FAQ: How can I use va
                
                
                
            
                        x=1 c1=string1 c2=string2 c3=string3 echo $c1 string1 我想通过使用类似的东西使输出为string1: 所以稍后在脚本中我可以增加x的值并输出string1,然后输出string2和string3. 谁能指出我正确的方向? 解决方法
 请参阅Bash FAQ: 
 How can I use variable variables (indirect variables,pointers,references) or associative arrays? 
  
  
        引用他们的例子: realvariable=contents
ref=realvariable
echo "${!ref}"   # prints the contents of the real variable 
 要说明这对您的示例有何用处: get_c() { local tmp; tmp="c$x"; printf %s "${!tmp}"; }
x=1
c1=string1
c2=string2
c3=string3
echo "$(get_c)" 
 当然,如果你想要正确的方式,只需要use an array: c=( "string1" "string2" "string3" )
x=1
echo "${c[$x]}" 
 请注意,这些数组是零索引的,所以x = 1时它会打印string2;如果你想要string1,你需要x = 0. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
