Bash: Создание массивов на лету, но не может получить к ним доступ позже - PullRequest
0 голосов
/ 26 февраля 2019

Я могу «по-видимому» успешно создавать массивы на лету, но потом не могу получить к ним доступ, что я делаю не так?
Обратите внимание, я прогуглил это до смерти и не могу найти хороший ответ.

Извините, за это лишнее словоблудие, но веб-сайт считает, что большая часть моего поста является кодом, и настаивает на дополнительных деталях ....

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 голосов
/ 26 февраля 2019

Чтобы действительно создать новый массив динамически, вам нужна переменная, чье значение является именем создаваемого массива.Небольшой пример.

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