20

在 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
4

1 回答 1

19

这个问题与采购无关;发生这种情况是因为作业numbers=${sourced_numbers[@]}没有按照您的想法进行。它将数组 ( sourced_numbers) 转换为一个简单的字符串,并将其存储在的第一个元素中numbers(在接下来的两个元素中保留“二”“三”)。要将其复制为数组,请numbers=("${sourced_numbers[@]}")改用。

顺便说一句,for number in ${numbers[@]}循环遍历数组元素是错误的方法,因为它会在元素中的空白处中断(在这种情况下,数组包含“一二三”“二”“三”,但循环运行“一”、“二”、“三”、“二”、“三”)。改为使用for number in "${numbers[@]}"。实际上,养成双引号几乎所有变量替换(例如echo "${numbers[${i}]}")的习惯是很好的,因为这不是唯一不加引号可能导致麻烦的地方。

于 2012-05-02T14:18:15.390 回答