diff --git a/bash.md b/bash.md index 40282a7f6..42602c41b 100644 --- a/bash.md +++ b/bash.md @@ -472,6 +472,53 @@ for i in "${arrayName[@]}"; do done ``` +Dictionaries +------------ +{: .-three-column} + +### Defining + +```bash +declare -A sounds +``` + +```bash +sounds[dog]="bark" +sounds[cow]="moo" +sounds[bird]="tweet" +sounds[wolf]="howl" +``` + +Declares `sound` as a Dictionary object (aka associative array). + +### Working with dictionaries + +```bash +echo ${sounds[dog]} # Dog's sound +echo ${sounds[@]} # All values +echo ${!sounds[@]} # All keys +echo ${#sounds[@]} # Number of elements +unset sounds[dog] # Delete dog +``` + +### Iteration + +#### Iterate over values + +```bash +for val in "${sounds[@]}"; do + echo $val +done +``` + +#### Iterate over keys + +```bash +for key in "${!sounds[@]}"; do + echo $key +done +``` + Options -------