Доступ к массиву по индексу в bash не работает #39; не работает правильно, если массив из исходного файла

В bash, когда я обращаюсь к массиву по индексу, я получаю странное поведение, если массив является переменной, которая была импортирована в исходный код другого скрипта bash. Что вызывает такое поведение? Как это можно исправить, чтобы массив, полученный из другого скрипта bash, вел себя так же, как массив, определенный из работающего скрипта?

${numbers[0]} оценивается как «один, два, три», а не как «один», как должно быть. Полный тест, который я попытался продемонстрировать, показан ниже.:

Источник test.sh:

#!/bin/bash

function test {

    echo "Length of array:"
    echo ${#numbers[@]}

    echo "Directly accessing array by index:"
    echo ${numbers[0]}
    echo ${numbers[1]}
    echo ${numbers[2]}

    echo "Accessing array by for in loop:"
    for number in ${numbers[@]}
    do
        echo $number
    done

    echo "Accessing array by for loop with counter:"
    for (( i = 0 ; i < ${#numbers[@]} ; i=$i+1 ));
    do
        echo $i
        echo ${numbers[${i}]}
    done
}

numbers=(one two three)
echo "Start test with array from within file:"
test 

source numbers.sh
numbers=${sourced_numbers[@]}
echo -e "\nStart test with array from source file:"
test

Источник number.sh:

#!/bin/bash
#Numbers

sourced_numbers=(one two three)

Вывод test.sh:

Start test with array from within file:
Length of array:
3
Directly accessing array by index:
one
two
three
Accessing array by for in loop:
one
two
three
Accessing array by for loop with counter:
0
one
1
two
2
three

Start test with array from source file:
Length of array:
3
Directly accessing array by index:
one two three
two
three
Accessing array by for in loop:
one
two
three
two
three
Accessing array by for loop with counter:
0
one two three
1
two
2
three
17
задан Mogsdad 24 August 2015 в 00:57
поделиться