如果数组来自源文件,则在bash中按索引访问数组无法正常工作

Reb*_*itz 17 arrays indexing bash

在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
Run Code Online (Sandbox Code Playgroud)

number.sh的来源:

#!/bin/bash
#Numbers

sourced_numbers=(one two three)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Gor*_*son 18

这个问题与采购无关; 它正在发生,因为任务numbers=${sourced_numbers[@]}没有按照你的想法去做.它将array(sourced_numbers)转换为一个简单的字符串,并将其存储在第一个元素中numbers(在接下来的两个元素中留下"两个""三个").要将其复制为数组,请numbers=("${sourced_numbers[@]}")改为使用.

BTW,for number in ${numbers[@]}是循环数组元素的错误方法,因为它会破坏元素中的空白(在这种情况下,数组包含"一二三""二""三",但循环运行"一" ","两个","三个","两个","三个").请for number in "${numbers[@]}"改用.实际上,养成几乎所有变量替换(例如echo "${numbers[${i}]}")的双重引用的习惯是好的,因为这不是唯一让他们不加引号的地方会引起麻烦.