Bash:动态创建数组,但以后无法访问它们

问题描述 投票:0回答:1

我可以“看似”成功地动态创建数组,但之后无法访问它们,我做错了什么? 请注意,我已经谷歌搜索死亡,无法找到一个好的答案。

对不起,对于这个额外的措辞,但该网站认为我的大多数帖子都是代码,并坚持额外的细节....

Code:
for i in `seq 1 3`;do
    echo "Attempting to create array$i ... count: '$count'"
    mytempvar=()
    mytempvar=$i
    echo "local mytempvar: '$mytempvar'"
    for j in `seq 1 $i`;do
        eval mytempvar+=($j)
    done
    echo "Printing out contents of array$i: '${mytempvar[@]}''"
    echo "Attempting to print out contents of array$i directly: '${i[@]}''"
done
for i in `seq 1 5`;do
    mytempvar=()
    mytempvar=$i
    echo "local mytempvar: '$mytempvar'"
    echo "Later: Attempting to print out contents of array$i: '${mytempvar[@]}''"
    echo "Later: Attempting to print out contents of array$i directly: '${i[@]}''"
done
Output:
./bash_test_varname_arrays.sh
Attempting to create array1 ...
i: '1' mytempvar: '1'
Printing out contents of array1: '1 1''
Attempting to print out contents of array1 directly: '1''
Attempting to create array2 ...
i: '2' mytempvar: '2'
Printing out contents of array2: '2 1 2''
Attempting to print out contents of array2 directly: '2''
Attempting to create array3 ...
i: '3' mytempvar: '3'
Printing out contents of array3: '3 1 2 3''
Attempting to print out contents of array3 directly: '3''
i: '1' mytempvar: '1'
Later: Attempting to print out contents of array1: '1''
Later: Attempting to print out contents of array1 directly: '1''
i: '2' mytempvar: '2'
Later: Attempting to print out contents of array2: '2''
Later: Attempting to print out contents of array2 directly: '2''
i: '3' mytempvar: '3'
Later: Attempting to print out contents of array3: '3''
Later: Attempting to print out contents of array3 directly: '3''
i: '4' mytempvar: '4'
Later: Attempting to print out contents of array4: '4''
Later: Attempting to print out contents of array4 directly: '4''
i: '5' mytempvar: '5'
Later: Attempting to print out contents of array5: '5''
Later: Attempting to print out contents of array5 directly: '5''
arrays bash var
1个回答
0
投票

要动态创建新数组,需要一个变量,其值是要创建的数组的名称。一个小例子。

for i in 1 2 3; do
    name=array$i
    declare -a "$name"
    declare "$name[0]=zero"
    declare "$name[1]=one"
done
# Proof the new variables exist
declare -p array1
declare -p array2
declare -p array3

但是,在bash 4.3中,使用namerefs会变得更容易。

for i in 1 2 3; do
   declare -n arr=array$i
   arr=(zero one)
done
© www.soinside.com 2019 - 2024. All rights reserved.