Saturday, June 04, 2011

Associative Arrays in Bash 4

Associative arrays allow you to store key-value pairs and retrieve values using their keys. You can think of them as maps (or hashes) in other programming languages. The following example illustrates how associative arrays can be used to map countries to their capital cities:
#!/bin/bash

#declare an associative array
declare -A capital

#there are different ways to populate the array:
capital=([UK]="London" [Japan]="Tokyo")

#or...
capital[Germany]="Berlin"
capital[China]="Beijing"

#you can even append using +=
capital+=([Belgium]="Brussels" [Egypt]="Cairo")

#print the number of entries
echo "Size: ${#capital[@]}"

#retrieve the capital of Germany
echo "Capital of Germany: ${capital[Germany]}"

#iterate over the keys and print all the entries
echo "Country -> Capital"
for country in "${!capital[@]}"
do
   echo "$country -> ${capital[$country]}"
done
Output:
Size: 6
Capital of Germany: Berlin
Country -> Capital
UK -> London
Germany -> Berlin
Belgium -> Brussels
China -> Beijing
Japan -> Tokyo
Egypt -> Cairo
Further reading:
Bash, version 4, Associative Arrays

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.