An associative array is an array indexed by string values.
It provides an association between the string index
and the value of the array at that index, making programming certain
kinds of tasks work much more naturally. You tell the shell that an
array is associative by using typeset -A:
typeset -A person
person[firstname]="frank"
person[lastname]="jones"
We can rewrite our terminal example from the previous section using associative arrays:
typeset -A termnames termnames is associative
termnames=([Givalt GL35a]=gl35a Fill in the values
[Tsoris T-2000]=t2000
[Shande 531]=s531
[Vey VT99]=vt99)
print 'Select your terminal type:'
PS3='terminal? '
select term in "${!termnames[@]}" Present menu of array indices
do
if [[ -n $term ]]; then
TERM=${termnames[$term]} Use string to index array
print "TERM is $TERM"
break
fi
done
Note that the square brackets in the compound assignment act like double quotes;
while it's OK to quote the string indices, it's not necessary.
Also note the "${!termnames[@]}" construct.
It's a bit of a mouthful, but it gives us all the array indices as
separate quoted strings that preserve any embedded whitespace, just like
"$@". (See the next section.)
Starting with ksh93j,
as for regular arrays,
you may use the +=
operator to add values to an associative array:
termnames+= ([Boosha B-27]=boo27 [Cherpah C-42]=chc42)
As a side note, if you apply typeset -A to a previously
existing nonarray variable,
that variable's current value will be placed in index 0.
The reason is that the shell treats
$x as equivalent to ${x[0]},
so that if you do:
x=fred
typeset -A x
print $x