2014-03-06 64 views
0

當我們將數組傳遞給bash腳本中的函數時,我們如何訪問元素?例如我有這樣的代碼:如何在傳遞給函數時訪問數組元素

check_corrects() { 
    local inp=$1[@] 
    echo # i want to echo inp[0] 
} 
a=(1 2 3) 
check_corrects a 

我怎麼回聲inp[0]

+0

'check_corrects a'不將數組或其任何部分傳遞給'check_corrects'。它傳遞一個單字符串「a」... – twalberg

回答

3

您不能將數組作爲參數傳遞給shell函數。參數是簡單編號的參數。您可能會導致一個數組成爲這些參數:

testa() { echo "$#"; } 
a=(1 2 3) 
testa "${a[@]}" 
3 

testa $a將回聲1,因爲它會的第一要素只有通過「a」到種皮。

但是這意味着,在你的情況下,如果你直接回顯數組擴展,你會得到第一個參數,這就是你想要的。

echo "$1" 
+0

謝謝@kojiro –

1

警告:前面的極端醜陋。不爲微弱的心臟:

check_corrects() { 
    local arrayref="$1[@]" 
    local array=("${!arrayref}") # gulp, indirect variable 
    local idx=$2 
    echo "${array[$idx]}" 
} 

現在,讓我們來測試

a=(1 2 "foo bar" 3) 
check_corrects a 2  # ==> "foo bar" 

唷。

不適用於關聯數組:「$ {ary [@]}」只返回值,而不是鍵。 另外,不能使用鍵不連續的數字數組。

1

只是對小次郎的回答,這是相當正確的闡述......

我經常做的時候我想傳遞的整個數組是這樣的:

foo() { 
    local a=("[email protected]") 
    ... 
} 

a=(1 2 3) 
foo "${a[@]}" 

這基本上重建值回放入foo()內部的數組中。請注意,如果單個數組元素的值可能包含空格,則引號是至關重要的。例如:

foo() { 
    local a=("[email protected]") 
    echo "foo: Number of elements in a: ${#a[@]}" 
} 

bar() { 
    local a=([email protected]) # wrong 
    echo "bar: Number of elements in a: ${#a[@]}" 
} 

a=(1 2 3 4) 
foo "${a[@]}" # Reports 4 elements, as expected 
bar "${a[@]}" # Also reports 4 elements, so where's the problem? 

a=("1 2" 3 "4 5 6") 
foo "${a[@]}" # Reports 3 elements, as expected 
bar "${a[@]}" # Reports 6 elements. Oops! 

編輯:雖然我的例子並沒有表現出來,把呼叫一側的報價也很重要。也就是說,如果您執行foo ${a[@]},則會遇到與上面示例中的bar相同的問題。底線是如果你的數組元素將包含空格,你需要使用引號。有關更詳細的解釋,請參閱What is the difference between [email protected] and $* in shell scripts?

相關問題