arrays - 如何连接两个字符串以创建变量名称

标签 arrays linux string bash concatenation

bash中有这样一个数组

array_1=(1 2 3 4 5)
array_2=(6 7 8  9 0)

我有另一个包含 1 或 2 的变量。

array_index=1

那么是否可以像这样使用该变量创建数组名称?

array_${array_index}[0]

最佳答案

使用变量间接读取和声明写入:

array_1=(1 2 3 4 5)
array_2=(6 7 8 9 0)
array_index=1
var="array_${array_index}[0]"

echo "The contents of $var is ${!var}"
declare "$var"="Something Else"
echo "Now $var contains ${!var} instead."

这比 eval 更安全、更容易正确使用。

关于arrays - 如何连接两个字符串以创建变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21693529/

相关文章:

python - 如何使用 NumPy 创建自定义 4x4 数组?

javascript - 仅获取数组中的 future 日期

linux - Docker 卸载 Sawtooth 市场

c++ - gcc 链接的默认库?

linux - Node 和 NPM linux 二进制安装

c++ - 为什么不能将一个字符串的索引位置分配给另一个字符串,但可以将其分配给中间字符?

javascript - 从 URL 中获取图像 byte/base64

将字符串中的值转换为 float 组

string - 如何将 D 中的 char* 转换为字符串?

python - 在 python 中拆分字符串