Last active
September 4, 2022 08:54
-
-
Save ar2pi/99dbcbbd023867aeee089bf65014cd20 to your computer and use it in GitHub Desktop.
Revisions
-
ar2pi revised this gist
Sep 4, 2022 . 1 changed file with 2 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -46,8 +46,8 @@ done #!/bin/bash arr=( "key value" "foo bar" ) for item in "${arr[@]}"; do -
ar2pi revised this gist
Sep 4, 2022 . 1 changed file with 4 additions and 4 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -2,7 +2,7 @@ ## bash **bash v3** ```bash function key_val () { @@ -18,7 +18,7 @@ for key in "foo" "baz"; do done ``` **bash v4** ```bash declare -A arr @@ -29,7 +29,7 @@ for key in ${!arr[@]}; do done ``` ## zsh ```zsh declare -A arr @@ -40,7 +40,7 @@ for key value in ${(kv)arr}; do done ``` ## Hacky cross-shell alternative ```sh #!/bin/bash -
ar2pi created this gist
Sep 4, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,59 @@ # Hash tables (associative arrays) in linux shell scripts ## bash ### bash v3 ```bash function key_val () { case $1 in "foo") echo "bar";; "baz") echo "qux";; *) echo "default";; esac } for key in "foo" "baz"; do echo "$key: $(key_val $key)" done ``` ### bash v4 ```bash declare -A arr arr=([foo]=bar [baz]=qux) for key in ${!arr[@]}; do echo "$key: ${arr[$key]}" done ``` ### zsh ```zsh declare -A arr arr=([foo]=bar [baz]=qux) for key value in ${(kv)arr}; do echo "$key: $value" done ``` ### Hacky cross-shell alternative ```sh #!/bin/bash arr=( "key value" "foo bar" ) for item in "${arr[@]}"; do key=$(echo $item | cut -d " " -f 1) value=$(echo $item | cut -d " " -f 2) echo "$key: $value" done ```