如何在bash中使用变量的值作为另一个变量的名称 [英] How to use a variable's value as another variable's name in bash

查看:36
本文介绍了如何在bash中使用变量的值作为另一个变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个变量,它的名字来自另一个变量的值,我写了如下一段代码:

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中使用变量的值作为另一个变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆