2012-04-11 88 views
1

出于某种原因,我无法用感叹号语法来访问数组键:访问bash的数组键(MAC)

declare -a sites 
sites=(["fr"]="frederick" ["an"]="annapolis") 

for i in "${!sites[@]}" 
    do 
    echo "key: $i " 
    done 

这只是呼应的出“键:0”

什么时我在这里做错了吗?

另外,我想添加该值。

所以我们放是:

键:FR,值:弗雷德里克

回答

1

问题是declare -a。根据手册页,应该是declare -A

declare [-aAfFgilrtux] [-p] [name[=value] ...] 
    ... 
    -a  Each name is an indexed array variable (see Arrays above). 
    -A  Each name is an associative array variable (see Arrays above). 

试试这个:

declare -A sites 
sites=(["fr"]="frederick" ["an"]="annapolis") 

for i in "${!sites[@]}" 
    do 
    echo "key: $i, value: ${sites[$i]}" 
    done 
+0

这就是我试图在第一。但如果我运行你发布的脚本,我得到这个输出:第3行:declare:-A:无效选项 declare:usage:declare [-afFirtx] [-p] [name [= value] ...] key :0,value:annapolis – jessh 2012-04-11 16:12:16

+0

这可能也有帮助:bash --version GNU bash,版本3.2.48(1) – jessh 2012-04-11 16:23:17

+6

关联数组需要bash> = 4.0。请参阅http://tiswww.case.edu/php/chet/bash/NEWS。事实上,你的bash 3.2手册页没有提及关联数组。 ;-) – Mikel 2012-04-11 17:38:59