What is Associative Array ?

Associative Array in shell script is to store key value pair.

Prerequisites:
Shell Bash version should be 4+.

Verify Shell Version
echo $BASH_VERSION
4.x.x(1)-release

Some points on Associative Array.

– Associative Array maintains key value pair
– Associative Array doesn’t maintain insertion order
– Associative Array overrides the entry if key is duplicated

How to Declare Associative Array ?

declare -A MYMAP=( ["hostname1"]="syspath1" ["hostname2"]="syspath2" ["hostname3"]="syspath3" )

 

How to iterate Associative Array ?

for KEY in "$!{MYMAP[@]}"
do
    echo "Key: "$KEY" Item: "${MYMAP[$KEY]}
done

How to Read Keys from Associative Array.

MYARRAY=("${!MYMAP[@]}")  # Array copy of $MYMAP Keys
#Array Iteration
for index in "${!MYARRAY[@]}"
do
     echo "key :" $index 
     echo "value:" ${MYARRAY[$index ]}
done

Enjoy !!

Advertisements