From 69f50888f42f52897fbd3949355d4f7026262ce0 Mon Sep 17 00:00:00 2001 From: Edson Ticona Date: Sun, 20 Jan 2019 13:18:13 +0100 Subject: [PATCH 1/2] Adds associative array usage --- bash.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/bash.md b/bash.md index 1e0d546e6..0a6adabda 100644 --- a/bash.md +++ b/bash.md @@ -464,6 +464,42 @@ for i in "${arrayName[@]}"; do done ``` +Dictionaries (Associative Arrays) +-------------------------------- + +### Defining + +```bash +declare -A sounds +``` + +```bash +sounds[dog]="bark" +sounds[cow]="moo" +sounds[bird]="tweet" +sounds[wolf]="howl" +``` + +### Working with dictionaries + +```bash +echo ${sounds[dog]} # Dog's sound +echo ${sounds[@]} # All the values +echo ${!sounds[@]} # All the keys +echo ${#sounds[@]} # Number of elements +unset sounds[dog] # Delete dog +``` + +### Iteration +```bash +for i in "${sounds[@]}"; do # Iterate over values + echo $i +done +for i in "${!sounds[@]}"; do # Iterate over keys + echo $i +done +``` + Options ------- From 8ea2be47310c733cedad48f7aad65d36acda89e9 Mon Sep 17 00:00:00 2001 From: "Rico Sta. Cruz" Date: Sat, 23 Mar 2019 22:26:44 +0800 Subject: [PATCH 2/2] Update formatting --- bash.md | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/bash.md b/bash.md index 0a6adabda..9d1dda6d2 100644 --- a/bash.md +++ b/bash.md @@ -464,8 +464,9 @@ for i in "${arrayName[@]}"; do done ``` -Dictionaries (Associative Arrays) --------------------------------- +Dictionaries +------------ +{: .-three-column} ### Defining @@ -480,23 +481,33 @@ 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 the values -echo ${!sounds[@]} # All the keys -echo ${#sounds[@]} # Number of elements -unset sounds[dog] # Delete dog +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 i in "${sounds[@]}"; do # Iterate over values - echo $i +for val in "${sounds[@]}"; do + echo $val done -for i in "${!sounds[@]}"; do # Iterate over keys - echo $i +``` + +#### Iterate over keys + +```bash +for key in "${!sounds[@]}"; do + echo $key done ```