如何使用变量的值作为bash的其他变量的名称

编程入门 行业动态 更新时间:2024-10-09 21:22:58
本文介绍了如何使用变量的值作为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的其他变量的名称

本文发布于:2023-11-28 20:29:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643848.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何使用   名称   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!