#!/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]}" doneOutput:
Size: 6 Capital of Germany: Berlin Country -> Capital UK -> London Germany -> Berlin Belgium -> Brussels China -> Beijing Japan -> Tokyo Egypt -> CairoFurther reading:
Bash, version 4, Associative Arrays
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.