在 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