Assign to dynamic variable name in Bash [duplicate

2020-07-23 06:03发布

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"

标签: linux shell unix
2条回答
Rolldiameter
2楼-- · 2020-07-23 06:51

With bash you can use declare:

declare var2_$var1="123"
查看更多
神经病院院长
3楼-- · 2020-07-23 06:58

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.

查看更多
登录 后发表回答