2016-06-21 42 views
0

內陣列的所有元素,我想我的數組轉儲到用戶,使他們能夠看到的映射會是什麼樣子。我嘗試了這樣的陳述printf '%s\n' "${cluster_to_endpoint[@]}"我試圖在下面的使用函數中轉儲它,但是我沒有得到我期待的輸出。慶典 - 如何轉儲使用

代碼進行:

#!/bin/bash 

set -e 

usage() { 
    echo "Usage: $0 -o oldcluster -n newcluster" 
    printf '%s\n' "${cluster_to_endpoint[@]}" 
} 

while getopts ":o:n:" opt; do 
    case $opt in 
    o) old="$OPTARG";; 
    n) new="$OPTARG";; 
    *) usage 
     exit 1 
     ;; 
    esac 
done 


# Mapping 
declare -A cluster_to_endpoint=(
     [c1]=foobar2-01.us-east-1.my.com 
     [c2]=foobar2-02.us-east-1.my.com 
     [c3]=foobar2-03.us-east-1.my.com 
     [c4]=foobar2-04.us-east-1.my.com) 

# Echo info 
echo "Source cluster:${cluster_to_endpoint[$old]}" 
echo "Target cluster:${cluster_to_endpoint[$new]}" 

輸出:

-bash-4.1$ ./tst.sh -h 
Usage: ./tst.sh -o oldcluster -n newcluster 

期待:

Usage: ./tst.sh -o oldcluster -n newcluster 

    [c1]=foobar2-01.us-east-1.my.com 
    [c2]=foobar2-02.us-east-1.my.com 
    [c3]=foobar2-03.us-east-1.my.com 
    [c4]=foobar2-04.us-east-1.my.com 
+4

你必須得到您期望的輸出,如果你創建數組* *前嘗試打印一個更好的機會。 – rici

回答

3

的代碼是從頂部執行底部,當它進入while循環,調用使用,它試圖打印您陣列,但它尚未初始化。

之前任何訪問把聲明語句。

1

初始化數組cluster_to_endpoint之前,你在呼喚你的usage外殼功能。

處理命令行之前移動declare語句。

除此之外,在一個陣列下標必須評估爲整數值,並且因此不能c1等你有。 編輯顯然這是你在Bash版本4+中做關聯數組的方式。舊的Bash需要使用帶有整數下標的普通數組(declare -a)。

+0

'declare -A'在Bash 4+中聲明一個關聯數組。它們由字符串鍵入。 –

+0

這是真的,忘了說我必須改變''a'爲'bash'我正在運行。如果它在你的'bash'版本中有效,那就去吧。平@noober – Kusalananda

+0

瞭解!感謝您的幫助 – noober