Skip to content Skip to main navigation Skip to footer

shell: bash关联数组

#声明一个数组

declare -A thearray

-a Each name is an indexed array variable (see Arrays above).

-A Each name is an associative array variable (see Arrays above). #没有这个说明bash的版本在4.0一下

关联数组的操作语法和数组的操作语法完全一致,如下常见的操作。

语法 描述

${!array[*]} 取关联数组所有键

${!array[@]} 取关联数组所有键

${array[*]} 取关联数组所有值

${array[@]} 取关联数组所有值

${#array[*]} 关联数组的长度

${#array[@]} 关联数组的长度

运行一下代码如果bash版本低于bash 4.0会有错误提示。升级后才能这样写。

#!/bin/bash
declare -A beatles
beatles=( [singer]=John [bassist]=Paul [drummer]=Ringo [guitarist]=George )
for musician in singer bassist drummer guitarist
do
  echo "The ${musician} is ${beatles[$musician]}.>"
done 

bash更新方式

下载地址:

http://ftp.gnu.org/gnu/bash/

当前最新bash http://ftp.gnu.org/gnu/bash/bash-4.3.tar.gz

wget http://ftp.gnu.org/gnu/bash/bash-4.3.tar.gz
tar zxvf bash-4.3.tar.gz
cd bash-4.3
./configure
make
make install
mv /bin/bash /bin/bash.bak; ln -s /usr/local/bin/bash /bin/bash 

原文:http://blog.oddfoo.net/2015/05/20/bash-associative-array/

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.