In bash when I access an array by index I get strange behavior if the array is a variable that was imported in the source of another bash script. What causes this behavior? How can it be fixed so an array that is sourced from another bash script behaves the same way as an array defined from within the running script?
${numbers[0]} evals to "one two three" and not "one" as it should.The full test I've tried to demonstrate this behavior is shown below:
Source of 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
Source of number.sh :
#!/bin/bash
#Numbers
sourced_numbers=(one two three)
Output of 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
set -vxwill show you something. (Don't have time to experiment right now). Good luck.