This question already has answers here:
how to use variable variable names in bash script [duplicate]
(1 answer)
Closed 3 years ago.
How do I assign a value to variable that has a variable in its name?
var1="file"
var2_$var1="folder"
The code above gives me the error -bash: var2_file=folder: command not found
. I was curious to know how to assign to a variable with another variable in its name.
Version of Bash is "GNU bash, version 4.1.2"
With bash
you can use declare
:
declare var2_$var1="123"
How about using another variable to hold the dynamic name and use it for retrieving the value after setting?
new_var=var2_$var1
declare var2_$var1="123"
echo "${!new_var}" # => 123
Unfortunately, Bash doesn't allow declare $new_var="123"
- that would have made this a little prettier.