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"

4
  • 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. Commented Feb 9, 2017 at 15:33
  • Why do you need it? There might be better ways to achieve your goal. Commented Feb 9, 2017 at 15:45
  • In 99% cases is better idea to use associative arrays. Commented Feb 9, 2017 at 15:51
  • BashFAQ #6 covers this in detail -- both associative arrays and indirect assignment as such. Commented Feb 9, 2017 at 18:00

2 Answers 2

5

With bash you can use declare:

declare var2_$var1="123"
Sign up to request clarification or add additional context in comments.

3 Comments

Would export work the same way? What about set?
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"
Yes, that's the problem with this approach. I recomend to use and assoc array instead
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.