Simulating hash tables in bash

On my previous blog (which I did not migrate), I posted this snippet to simulate hash tables in bash. Is it useful? Maybe. In any case, this is an slightly improved version which allows ‘values’ to have spaces in them. Apparently (I’ve never tested it before today), this was kind of a problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
hash_table=(
    key1='value1'
    key2='value2'
)
 
hash_get() {
    local _table="$1";
    local _key="$2";
    local _value="${_table}[@]";
    local "${!_value}";
    eval echo "\$${_key}";
}
 
hash_get "hash_table" "key2";