在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
答案 0 :(得分:17)
问题与采购无关;它正在发生,因为作业numbers=${sourced_numbers[@]}
没有按照你的想法去做。它将数组(sourced_numbers
)转换为一个简单的字符串,并将其存储在numbers
的第一个元素中(在接下来的两个元素中留下“两个”“三个”)。要将其复制为数组,请改用numbers=("${sourced_numbers[@]}")
。
for number in ${numbers[@]}
是循环数组元素的错误方法,因为它会破坏元素中的空白(在这种情况下,数组包含“一二三”“二”“三” ,但循环运行“一”,“两”,“三”,“两”,“三”)。请改用for number in "${numbers[@]}"
。实际上,养成几乎所有变量替换(例如echo "${numbers[${i}]}"
)的习惯是很好的,因为这不是唯一让他们不加引号的地方可能会引起麻烦。