且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在bash中使用变量的值作为另一个变量的名称

更新时间:2023-01-08 09:51:58

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.)