9.3 关联数组

关联数组是bash 4.0新增的一个特性。关联数组将值与索引连接(关联)到一起,所以我们可以将元数据与实际数据关联起来。使用这种方式可以将音乐家与他的乐器联系起来。关联数组必须以大写的declare -A命令来进行声明。
 
cat musicians.sh
#!/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
./musicians.sh
The singer is John.
The bassist is Paul.
The drummer is Ringo.
The guitarist is George.
$

在bash引入关联数组之前,${beatles[index]没有任何意义。它会被自动解释为${beatles[$index]。然而,因为关联数组可以将文本作为其索引,所以现在使用${beatles["index"]}是合法的。因此关联数组中必须使用美元符号。如果省略美元符号,解释为数组索引的将会是单词index,而不是变量$index的值。

关联数组更有用的功能是对索引的名称进行反向引用。这意味着如果给定了乐器的名称,我们可以得到音乐家的名字。同样地,给定了音乐家的名字,我们可以确定乐器。反向引用的语法是${!array[@]}。 

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

$


出处:https://book.2cto.com/201209/3570.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值