问题描述
我想声明一个变量,其名称来自另一个变量的值,我编写了以下代码:
I want to declare a variable, the name of which 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 get this job done?
推荐答案
eval
用于此目的,但是如果您天真地这样做,将会有令人讨厌的转义问题.这种事情通常是安全的:
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
转义美元符号可以解决所有逃生问题.美元符号可以逐字保存到eval
函数中,该函数将有效地执行此操作:
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中将变量的值用作另一个变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!