Skip to content

Instantly share code, notes, and snippets.

@ar2pi
Last active September 4, 2022 08:54
Show Gist options
  • Select an option

  • Save ar2pi/99dbcbbd023867aeee089bf65014cd20 to your computer and use it in GitHub Desktop.

Select an option

Save ar2pi/99dbcbbd023867aeee089bf65014cd20 to your computer and use it in GitHub Desktop.

Revisions

  1. ar2pi revised this gist Sep 4, 2022. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions doc.md
    Original file line number Diff line number Diff line change
    @@ -46,8 +46,8 @@ done
    #!/bin/bash

    arr=(
    "key value"
    "foo bar"
    "key value"
    "foo bar"
    )

    for item in "${arr[@]}"; do
  2. ar2pi revised this gist Sep 4, 2022. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions doc.md
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@

    ## bash

    ### bash v3
    **bash v3**

    ```bash
    function key_val () {
    @@ -18,7 +18,7 @@ for key in "foo" "baz"; do
    done
    ```

    ### bash v4
    **bash v4**

    ```bash
    declare -A arr
    @@ -29,7 +29,7 @@ for key in ${!arr[@]}; do
    done
    ```

    ### zsh
    ## zsh

    ```zsh
    declare -A arr
    @@ -40,7 +40,7 @@ for key value in ${(kv)arr}; do
    done
    ```

    ### Hacky cross-shell alternative
    ## Hacky cross-shell alternative

    ```sh
    #!/bin/bash
  3. ar2pi created this gist Sep 4, 2022.
    59 changes: 59 additions & 0 deletions doc.md
    Original 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
    ```