问题描述
我知道 bash 支持使用 !
运算符的间接变量引用:
I know that bash supports indirect variable references using the !
operator:
$ ABC=123
$ DEF=ABC
$ echo ${!DEF}
123
这很好.但是 - 当我想设置一个变量的值时,它似乎不起作用,我从另一个变量获得它的名字:
and that's nice. But - it doesn't seem work when I want to set the value of a variable, whose name I get from another variable:
$ ABC=123
$ DEF=ABC
$ !DEF=1234
-bash: !DEF=1234: event not found
$ ${!DEF}=1234
-bash: 123=1234: command not found
除了使用 eval
- 我如何设置一个变量的值,该变量的名称是另一个变量的值?
Other than by using eval
- how can I set the value of a variable whose name is the value of another variable?
推荐答案
关于您的问题
...我想设置一个变量的值,我从另一个变量中得到它的名字...如何设置名称为另一个变量值的变量的值?
您可以在 Bash 中的动态变量名称中找到答案.还提到了其他选项,例如 read
、printf
或 declare
.
you may find the answer in Dynamic variable names in Bash. There are further options like read
, printf
or declare
mentioned.
您可以在
或 为什么在 Bash 中应该避免 eval ,我应该使用什么来代替? 关于如何使 eval
安全?.
Or Why should eval be avoided in Bash, and what should I use instead? about How to make eval
safe?.
这篇关于bash 中的间接左值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!