Shell 在unix中使用变量作为变量名的一部分
我想把变量命名为Shell 在unix中使用变量作为变量名的一部分,shell,unix,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,不想更
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,不想更改变量名,即不想将值赋给另一个值。在bash中,您可以执行以下操作(注意最后一行中的感叹号语法):
参数扩展不是递归的,因此文本
${a_${v}
实际上是名为'a_${v}'的变量的内容
,shell抱怨此变量名无效
您可以使用eval
命令实现递归扩展,如中所示
eval printf '%s\n' "\${a_${v}}"
为了提高shell脚本的可读性和可维护性,您应该限制此类结构的使用,并将其封装在适当的结构中。有关示例,请参阅FreeBSD系统上提供的。在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
@Pumbaa80您引用的问题(及其答案)是特定于bash的
bash
,对于这个问题有一个可移植的、非特定于bash的答案可能很有用。简单:删除最后一行,改为执行以下两行:varname=$(echo“a_${v}”)
后跟echo${!varname}
。不客气:D我会将此作为答案添加,但不会让我这样做:/这不是重复的!需要/bin/sh的答案而不是BASH,并且不使用eval(如果可能)。所有链接的答案都不能满足此要求。这个小示例节省了大量时间-谢谢!!
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