Skip to content

Instantly share code, notes, and snippets.

@ar2pi
Last active September 4, 2022 08:54
Show Gist options
  • Save ar2pi/99dbcbbd023867aeee089bf65014cd20 to your computer and use it in GitHub Desktop.
Save ar2pi/99dbcbbd023867aeee089bf65014cd20 to your computer and use it in GitHub Desktop.
Hash tables (associative arrays) in linux shell scripts

Hash tables (associative arrays) in linux shell scripts

bash

bash v3

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

declare -A arr
arr=([foo]=bar [baz]=qux)

for key in ${!arr[@]}; do 
    echo "$key: ${arr[$key]}"
done

zsh

declare -A arr
arr=([foo]=bar [baz]=qux)

for key value in ${(kv)arr}; do 
    echo "$key: $value"
done

Hacky cross-shell alternative

#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment