Bash - Dictionary Hash Key / Value Pairs using Arrays

#!/bin/bash getValueByKey () { # separator: key=left value=right local sep="::" local array_name=$1 local k=$2 local var=$3 for i in "$@" ; do case $i in -k=*|--key=*) local k="${i#*=}" ;; -a=*|--array=*) local array_name="${i#*=}" ;; -v=*|--var=*) local var="${i#*=}" ;; -s=*|--sep=*) local sep="${i#*=}" ;; esac done local tmp=$array_name[@] local array=( "${!tmp}" ) # loop through values for index in "${array[@]}" ; do #left of $sep local KEY="${index%%$sep*}" #right of $sep local VALUE="${index##*$sep}" if [ "$k" = "$KEY" ] ; then if [ -z "$var" ] ; then # no variable passed # just echo the result echo "$VALUE" else # result will set variable passed by name eval $var="'$VALUE'" fi fi done } hash1=( 'hello::world' 'nice,to meet you' 'foo::bar' 'abc=123' 'outlier_key+++outlier_value' 'saucer_key<>saucer_value' ) value_1=$(getValueByKey hash1 "hello"); getValueByKey hash1 "foo" value_2; getValueByKey -a="hash1" -k="abc" -v=value_3 -s="="; getValueByKey --array=hash1 --key="nice" --var=value_4 --sep=","; getValueByKey --array=hash1 --key="outlier_key" --var=value_5 --sep="+++"; getValueByKey --array=hash1 --key="saucer_key" --var=value_6 --sep="<>"; echo echo "test 1) "$value_1; echo "test 2) "$value_2; echo "test 3) "$value_3; echo "test 4) "$value_4; echo "test 5) "$value_5; echo "test 6) "$value_6; echo : ' test 1) world test 2) to meet you test 3) 123 test 4) bar test 5) outlier_value test 6) saucer_value ' hash2=( 'hello::goodnight' 'nice::day today' 'foo::baz' 'abc::xyz' ) value_1=$(getValueByKey hash2 "hello"); getValueByKey hash2 "nice" value_2; getValueByKey -a="hash2" -k="abc" -v=value_3 -s="::"; getValueByKey --array=hash2 --key="foo" --var=value_4 -sep="::"; echo echo "test 1) "$value_1; echo "test 2) "$value_2; echo "test 3) "$value_3; echo "test 4) "$value_4; echo : ' test 1) goodnight test 2) day today test 3) xyz test 4) baz '

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.