Assign to dynamic variable name in Bash [duplicate]

為{幸葍}努か 提交于 2020-07-05 11:37:26

问题


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"


回答1:


With bash you can use declare:

declare var2_$var1="123"



回答2:


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.



来源:https://stackoverflow.com/questions/42140662/assign-to-dynamic-variable-name-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!