我要声明其名称来自另一个变量的值的变量,而我写的下面这段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的其他变量的名称
发布评论