bash中数组的动态变量名称 [英] Dynamic variable names for an array in bash
本文介绍了bash中数组的动态变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为循环"的数组.
I have an array called "loop".
对于循环"中的每个元素,我想创建一个数组,其名称包含当前元素的文本.
For each element in "loop" I want to create an array whose name contains the text of the current element.
然后我想遍历每个新数组并打印每个数组中的每个元素.
I then want to loop through each new array and print every element from each array.
这篇文章似乎对变量有很好的解决方案,但我不知道如何使其适用于数组.
This post seems to have a good solution for variables but I do not know how to adapt it to work for arrays.
我的脚本
#!/bin/bash
loop=(
first
second
third
)
for word in "${loop[@]}"
do
declare "${word}_holder=( hello world )"
var="${word}_holder"
echo "$var"
for i in "${!var}[@]"
do
echo "$i"
done
done
当前输出
first_holder
( hello world )[@]
second_holder
( hello world )[@]
third_holder
( hello world )[@]
所需的输出
first_holder
hello
world
second_holder
hello
world
third_holder
hello
world
推荐答案
虽然不漂亮,但这只是一个开始:
It ain't pretty, but it's a start:
#!/bin/bash
loop=(
first
second
third
)
for word in "${loop[@]}"
do
var=${word}_holder
eval "declare -a ${var}"
eval "${var}=( Hello World )"
eval 'nEntries=${#'${var}'[@]}'
echo ${var}
for (( ii=0; ii<$nEntries; ii++ )); do
cmd='echo ${'${var}'['$ii']}'
eval ${cmd}
done
done
这篇关于bash中数组的动态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文