关联数组是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
$ 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