如何使用变量的值作为bash的其他变量的名称 [英] how to use a variable's value as other variable's name in bash
问题描述
我要声明其名称来自另一个变量的值的变量,而我写的
下面这段code的:
I want to declare a variable which name comes from the value of another variable, and I wrote the following piece of code:
a="bbb"
$a="ccc"
但它没有工作。是什么让这个完成工作的正确方法?
but it didn't work. what's the right way to let this job done?
推荐答案
评估
用于这一点,但如果你这样做天真的,有将是讨厌的转义的问题。这种事情一般是安全的:
eval
is used for this, but if you do it naively, there are going to be nasty escaping issues. This sort of thing is generally safe:
name_of_variable=abc
eval $name_of_variable="simpleword" # abc set to simpleword
这打破了:
eval $name_of_variable="word splitting occurs"
解决方法:
eval $name_of_variable="\"word splitting occurs\"" # not anymore
最终修正:将要分配到一个变量的文本。让我们把它叫做 safevariable
。然后,你可以这样做:
The ultimate fix: put the text you want to assign into a variable. Let's call it safevariable
. Then you can do this:
eval $name_of_variable=\$safevariable # note escaped dollar sign
逃离美元符号解决所有问题逃生。美元符号逐字生存到评估
功能,这将有效地执行这样的:
Escaping the dollar sign solves all escape issues. The dollar sign survives verbatim into the eval
function, which will effectively perform this:
eval 'abc=$safevariable' # dollar sign now comes to life inside eval!
当然,这种分配是免疫一切。 safevariable
可以包含 *
,空格 $
等。 (需要说明的是,我们正在假设 NAME_OF_VARIABLE
包含什么,但一个有效的变量名,一个大家都可以自由使用。没有什么特别)
And of course this assignment is immune to everything. safevariable
can contain *
, spaces, $
, etc. (The caveat being that we're assuming name_of_variable
contains nothing but a valid variable name, and one we are free to use: not something special.)
这篇关于如何使用变量的值作为bash的其他变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!