在unix中使用变量作为变量名的一部分

时间:2014-09-07 09:26:22

标签: shell unix

我想将变量命名为a_${v}

例如:v可以是2013 2014

我现在将变量声明为a_${v}

a_${v}=hI # a_2013 should be Hi

v=2014

所以a_${v}=Hello # a_2014应该是Hello

我尝试使用eval命令虽然在分配值时没有抛出错误但是我无法提取变量名的值

$ v=2013

$ eval a_${v}=Hi


$ v=2014

$ eval a_${v}=Hello

echo ${a_${v}}

无效.. :(

我正在使用bash而我不想更改变量名,即dn想要将值分配给另一个值

3 个答案:

答案 0 :(得分:3)

在bash中,您可以执行以下操作(请注意最后一行中的感叹号语法):

#!/bin/bash

a_2014='hello 2014'
year=2014
varname=a_${year}
echo ${!varname}

答案 1 :(得分:1)

参数扩展不是递归的,因此文本${a_${v}}实际上是The contents of the variable whose name is 'a_${v}',并且shell抱怨此变量名无效。

您可以使用eval命令实现递归扩展,如

eval printf '%s\n' "\${a_${v}}"

为了提高shell脚本的可读性和可维护性,您应该限制此类构造的使用并将它们包装在适当的结构中。有关示例,请参阅FreeBSD系统上提供的rc.subr

答案 2 :(得分:0)

在bash 4.3中也是:

txt="Value of the variable"

show() { echo "indirect access to $1: ${!1}"; }

a_2014='value of a_2014'
echo "$txt \$a_2014: $a_2014"
show a_2014                    # <-------- this -----------------------+
                               #                                       |
prefix=a                       #                                       |
year=2014                      #                                       |
string="${prefix}_${year}"     #                                       |
echo "\$string: $string"       #                                       |
show "$string"            #$string contains a_2014 e.g. the same as ---+

echo ===4.3====
#declare -n  - only in bash 4.3
#declare -n refvar=${prefix}_${year}
#or
declare -n refvar=${string}

echo "$txt \$refvar: $refvar"
show refvar

echo "==assign to refvar=="
refvar="another hello 2014"
echo "$txt \$refvar: $refvar"
echo "$txt \$a_2014: $a_2014"
show a_2014
show "$string" #same as above
show refvar

打印

Value of the variable $a_2014: value of a_2014
indirect access to a_2014: value of a_2014
$string: a_2014
indirect access to a_2014: value of a_2014
===4.3====
Value of the variable $refvar: value of a_2014
indirect access to refvar: value of a_2014
==assign to refvar==
Value of the variable $refvar: another hello 2014
Value of the variable $a_2014: another hello 2014
indirect access to a_2014: another hello 2014
indirect access to a_2014: another hello 2014
indirect access to refvar: another hello 2014
相关问题