bash で配列にインデックスでアクセスすると、配列が別の bash スクリプトのソースにインポートされた変数である場合、奇妙な動作が発生します。この動作の原因は何ですか? 別の bash スクリプトから供給された配列が、実行中のスクリプト内から定義された配列と同じように動作するようにするにはどうすれば修正できますか?
${numbers[0]} は、本来の「1」ではなく「1 2 3」に評価されます。この動作を実証するために試みた完全なテストを以下に示します。
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