问题
I want to name variable as a_${v}
.
for example : v can be 2013 2014
I am now declaring a variable to a_${v}
a_${v}=hI # a_2013 should be Hi
v=2014
so a_${v}=Hello # a_2014
should be Hello
I tried using eval command though it is not throwing error while assigning a value but I am not able to extract the value of variable name
$ v=2013
$ eval a_${v}=Hi
$ v=2014
$ eval a_${v}=Hello
echo ${a_${v}}
is not working.. :(
I am using bash and I don't want to change the variable name i.e dn't want to assign the value to another value
回答1:
In bash you can do the below (note the exclamation mark syntax in the last line):
#!/bin/bash
a_2014='hello 2014'
year=2014
varname=a_${year}
echo ${!varname}
回答2:
Parameter expansion is not recursive, therefore the text ${a_${v}}
is really The contents of the variable whose name is 'a_${v}'
, and the shell complains that this variable name is not valid.
You can achieve recursive expansion with the eval
command, as in
eval printf '%s\n' "\${a_${v}}"
To increase the readability and maintainability of your shell scripts, you should limit the use of such constructs and wrap them in appropriate structures. See rc.subr provided on FreeBSD systems for an example.
回答3:
In bash 4.3 also:
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
prints
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
来源:https://stackoverflow.com/questions/25708811/using-variables-as-part-of-variable-name-in-unix