Drunken abuse of the filesystem to implement associative arrays in shell

Adrien Kunysz, Thu, Oct 17 2013 04:41:21 CEST

About one month ago I was sitting in the supposedly oldest pub of Dublin with a couple of Serbian dudes. We ended up discussing shell scripting.

- You could do it [no I don't remember what "it" was] easily in Bash with an associative array but that doesn't exist in POSIX shell.
- Well, you can always reimplement them.
- That's going to take a lot of code.
[30 seconds pause]
- Actually, there is a very easy way.
# No argument.
# Print symbolic name for the new associative array on stdout,
# later referred to as "$ht".
hcreate() {
    mktemp -d --tmpdir

# hput $ht $key $value
# Set the value of $key to $value in $ht.
hput() {
    echo "$3" > "$1/$2"

# hexists $ht $key
# Return success iff $key exists in $ht.
hexists() {
    test -f "$1/$2"

# hget $ht $key
# Print the value of $key in $ht on stdout.
hget() {
    cat "$1/$2"

# hdel $ht $key
# Remove the key $key from $ht.
hdel() {
    rm "$1/$2"

# hdestroy $ht
# Release all resources associated to $ht.
hdestroy() {
    rm -r "$1"

There are some obvious limitations that can be easily fixed but I am aiming for brevity here:

As for the performance discussion, I leave that to the readers.

Back to all articles.