The lazy programmer scripts
scripts that work

Lazy pro usage of bash associative arrays (dictionaries) GitHub

This is an example on how to leverage dictionaries like contraptions in bash.

Tested on RHEL 7, Ubuntu 14.04, 16.04

#!/bin/bash
set -e

ASSOC_ARRAY_KEYS=("KEY1" "KEY2")
KEY1_VAL="VAL1"
KEY2_VAL="VAL2"

for ASSOC_ARRAY_KEY in ${ASSOC_ARRAY_KEYS[@]}; do
    VAL_REF="${ASSOC_ARRAY_KEY}_VAL"
    echo "${!VAL_REF}"
    # it should print VAL1 and VAL2
    # if you want to change the value of a certain key
    NEW_VALUE_FOR_KEY1="VAL_NEW"
    eval $VAL_REF=\"\$\{NEW_VALUE_FOR_KEY1\}\"
    echo "${!VAL_REF}"
    # it should print VAL_NEW
done

That's all, folks!

Written by kami on Thursday May 31, 2018
Permalink - Tags: linux, bash, centos, ubuntu, dictionaries, associative-arrays

Leave a comment

comments powered by Disqus

« Lazy configure Ubuntu minimal desktop and VNC - Lazy remove pesky files on Windows »