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

7

我希望将变量命名为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,不想改变变量名称,即不想将值分配给另一个变量。


1
@Pumbaa80,你引用的问题(以及它的答案)是针对bash的,而有一个可移植的、非bash特定的答案对于这个问题也是有用的。 - Michaël Le Barbier
简单来说,删除你的最后一行代码,用以下两行代码替换:varname=$(echo "a_${v}"),然后是 echo ${!varname}。不用谢 :D 我本想将其作为答案添加,但系统不允许 :/ - CommaToast
这不是重复问题!需要针对/bin/sh而非BASH进行答案解决,并尽可能避免使用eval。没有任何链接的答案能够满足此要求。 - user9645
3个回答

11

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

#!/bin/bash

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

这个小例子节省了很多时间 - 谢谢!! - somshivam

2
参数扩展不是递归的,因此文本${a_${v}}实际上是'a_${v}'变量名称的内容,而shell会抱怨这个变量名无效。
您可以使用eval命令实现递归扩展,如下所示:
eval printf '%s\n' "\${a_${v}}"

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接