Associative arrays (hash, dictionary) on bash

This is how to create associative arrays (hash, dictionary) on bash:

#!/bin/bash
if [ "$1" == "help" ]
    then
    echo "Help";
    echo "USAGE:";
    echo "========";
    echo "purge_landingpage_varnish.sh LIVE|STAGE";
    exit 0;
elif [ $1 ]
    then
    DOMAINS['LIVE']="www.ask-sheldon.com";
    DOMAINS['STAGE']="stage.ask-sheldon.com;

    REQUEST_DOMAIN="";
    if [ "$1" == "LIVE" -o "$1" == "STAGE" ]
        then
        REQUEST_DOMAIN=${DOMAINS["$1"]};
    else
        echo "You have to give me the right instance parameters Master!!!";
        exit -1;
    fi
    STORES=(
        'de_de' \
        'at_de' \
        'be_en' \
        'bg_en' \
        'ch_de' \
        'cy_en' \
        'cz_en' \
        'dk_en' \
        'ee_en' \
        'es_en' \
        'fi_en' \
        'fr_fr' \
        'gr_en' \
        'hu_en' \
        'ie_en' \
        'it_en' \
        'lt_en' \
        'lu_en' \
        'lv_en' \
        'mt_en' \
        'nl_nl' \
        'pl_en' \
        'pt_en' \
        'ro_en' \
        'se_en' \
        'si_en' \
        'sk_en' \
        'uk_en'
    );

    for sStore in ${STORES[@]}
    do
        echo  "WILL RUN  curl --include -X PURGE --header \"Host: $REQUEST_DOMAIN\" 192.168.73.11/$sStore/ now!!!";
        curl --include -X PURGE --header "Host: $REQUEST_DOMAIN" 192.168.73.11/$sStore/;
        echo  "DID RUN  curl --include -X PURGE --header \"Host: $REQUEST_DOMAIN\" 192.168.73.11/$sStore/ !!!";
    done;
else
    echo "You have to give me the right params!!!";
    exit -1;
fi

This script was made to purge the varnish on one of my clusters. But the important stuff is the declaration of the associative array with DOMAINS[‘LIVE’]=”www.ask-sheldon.com”; and how to access the values of the array (with REQUEST_DOMAIN=${DOMAINS[“$1”]};). “$1” is the array key to select the value.
By the way, you can see how to crate a multi-line array (STORES) and how to run through it within a foreach loop (for sStore in ${STORES[@]} do […] done; ).

Leave a Reply

Your email address will not be published.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.