Using variables as part of a variable name in unix

I want to name the variable as a_${v} .

for example: v maybe 2013 2014

Now I declare a_${v} variable

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

therefore a_${v}=Hello # a_2014 must be Hello

I tried to use the eval command, although it does not throw an error when assigning a value, but I cannot extract the value of the variable name

 $ v=2013 $ eval a_${v}=Hi $ v=2014 $ eval a_${v}=Hello echo ${a_${v}} 

does not work..: (

I use bash and I do not want to change the variable name ie dn't want to assign a value to another value

+5
source share
3 answers

In bash, you can do the following (note the exclamation point syntax in the last line):

 #!/bin/bash a_2014='hello 2014' year=2014 varname=a_${year} echo ${!varname} 
+1
source

The parameter extension is not recursive, so the text ${a_${v}} 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 a recursive extension with the eval command, as in

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

To increase the readability and serviceability of your shell scripts, you should limit the use of such constructs and wrap them in appropriate structures. For an example, see rc.subr provided on FreeBSD systems.

0
source

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 eg 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 
0
source

Source: https://habr.com/ru/post/1202001/


All Articles