当我通过索引访问数组时,如果数组是在另一个bash脚本的源代码中导入的变量,我会得到奇怪的行为.是什么原因导致这种行为?它如何被修复,所以来自另一个bash脚本的数组的行为与从运行脚本中定义的数组相同?
${numbers [0]} evals to“one two three”而不是“one”,因为它应该是.我试图演示这个行为的全面测试如下所示:
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
来源of.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
这个问题与采购无关.这是因为作业编号= ${sourced_numbers [@]}不会执行您的想法.它将数组(sourced_numbers)转换成一个简单的字符串,并将其存储在数字的第一个元素中(在接下来的两个元素中留下“两个”“三”).要将其复制为数组,请改用数字=(“${sourced_numbers [@]}”).
原文链接:https://www.f2er.com/bash/386490.html对于${numbers [@]}中的数字来说,BTW是循环遍历数组元素的错误方式,因为它将会在元素中的空格上破坏(在这种情况下,数组包含“一二三”“二”三“,但循环运行为”一“,”二“,”三“,”三“).用于“${numbers [@]}”中的号码.实际上,很容易得到双引号的习惯,几乎所有的变量替换(例如echo“${numbers {${i}]}”),因为这不是让他们不引用的唯一的地方可能会导致麻烦.