6

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"

codeforester
  • 39,467
  • 16
  • 112
  • 140
vardhan
  • 1,377
  • 11
  • 14
  • This is very shell specific. What shell are you using? Bash (from the error message)? Please list the version as well. Do not respond in a comment. Please edit the question itself. – Mad Physicist Feb 09 '17 at 15:33
  • Why do you need it? There might be better ways to achieve your goal. – choroba Feb 09 '17 at 15:45
  • In 99% cases is better idea to use associative arrays. – clt60 Feb 09 '17 at 15:51
  • [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006) covers this in detail -- both associative arrays *and* indirect assignment as such. – Charles Duffy Feb 09 '17 at 18:00

2 Answers2

5

With bash you can use declare:

declare var2_$var1="123"
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    Would `export` work the same way? What about `set`? – Mad Physicist Feb 09 '17 at 15:37
  • Thanks alot for both of your answers. I tried `export`, `set` and `declare` all worked fine. But know how to retrieve value of it.!! `echo $var2_$var1` The output of it should be "123" – vardhan Feb 09 '17 at 15:44
  • Yes, that's the problem with this approach. I recomend to use and assoc array instead – hek2mgl Feb 09 '17 at 15:50
0

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140