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
However, if you simply want to store some data in a key-value fashion, you can use a dictionary: var data = new Dictionary<string, decimal>(); The first type argument is the key, and the second is the value. Do note that the values all have to be of the same type, or a type that derives from some common type.
You can simply store the name of the variable in an indirection variable, not unlike a C pointer. Bash then has a syntax for reading the aliased variable: ${! name} expands to the value of the variable whose name is the value of the variable name . You can think of it as a two-stage expansion: ${!
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With