20

bash で配列にインデックスでアクセスすると、配列が別の bash スクリプトのソースにインポートされた変数である場合、奇妙な動作が発生します。この動作の原因は何ですか? 別の bash スクリプトから供給された配列が、実行中のスクリプト内から定義された配列と同じように動作するようにするにはどうすれば修正できますか?

${numbers[0]} は、本来の「1」ではなく「1 2 3」に評価されます。この動作を実証するために試みた完全なテストを以下に示します。

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(次の 2 つの要素に "two" "three" を残して) の最初の要素に格納します。配列としてコピーするには、numbers=("${sourced_numbers[@]}")代わりに使用します。

ところで、for number in ${numbers[@]}配列の要素をループするのは間違った方法です。要素内の空白で壊れるためです (この場合、配列には「one two three」「two」「three」が含まれていますが、ループは「one」に対して実行されます)。 "、"2"、"3"、"2"、"3")。for number in "${numbers[@]}"代わりに使用してください。実際には、ほぼすべての変数置換 (例: echo "${numbers[${i}]}") を二重引用符で囲む習慣を身に付けるのは良いことです。

于 2012-05-02T14:18:15.390 に答える