I'm wondering if there is something like C++'s std::map in bash? I
want to use a key to look up a value from the map.
Thanks,
Peng
My bash version doesn't seem to support hash tables, not sure about
more recent versions.
But would it be an option to switch to ksh93...?
typeset -A h
h[Hello]=World
key=Hello
print - ${h[$key]}
Janis
>
> Thanks,
> Peng
A bash array can be used if you are willing to convert your key to an
integer. This might be done, for example, by converting each letter to an
integer from 01 to 26. The bash man page says that arrays are unlimited in
size. Not sure if there is a practical limit but the following code
doesn't run into it.
================ cut =====================================================
#!/bin/bash
function make_key()
{
# Process each letter in the key (we will only support lowercase).
# There must be a better way but I can't think of it right now so
# brute force it is!
local letters="$1"
local key=1 # be sure not interpreted as octal
local -a ltrs=( a b c d e f g h i j k l m n o p q r s t u v w x y z )
local -a nbrs=( 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 )
while [ "$letters" ] ; do
local ltr=${letters:0:1}
local letters=${letters:1}
local n=0
while ((n<27)) ; do
[ "${ltrs[$n]}" = "$ltr" ] && {
key=${key}${nbrs[$n]}
break
}
((++n))
done
done
echo $key
}
declare -a MYARRAY
function insert_value()
{
local key=$(make_key "$1")
MYARRAY[$key]="$2"
}
insert_value somekey Hello
insert_value someotherkey Sailor
echo "My Message: ${MYARRAY[$(make_key somekey)]} ${MYARRAY[$(make_key someotherkey)]}!"
================ cut =====================================================
Output is "Hello Sailor!"