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

时间:2019-02-26 17:52:01

标签: arrays bash var

我可以“看似”成功地动态创建数组,但之后无法访问它们,这是我做错了吗?
请注意,我已经对此进行了谷歌搜索,找不到合适的答案。

对不起,这个多余的字眼,但是网站认为我的大部分帖子都是代码,并坚持提供更多细节。...

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''

1 个答案:

答案 0 :(得分:0)

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

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中,使用名称引用变得更加容易。

for i in 1 2 3; do
   declare -n arr=array$i
   arr=(zero one)
done