Search code examples
arraysbashassociative-array

Check if associative array element exists in bash


In a bash script, I have a locale in a variable like so

locale=fr_ma

I also have an associative array like this

declare -A new_loc_map
new_loc[fr_ma]=en_ma
new_loc[el_gr]=en_gr
new_loc[sl_si]=en_si

I want to check if new_loc element with the key ${locale} exists

I thought this should work but it doesn't:

if [[ -v "${new_loc[${locale}]}" ]]
    then
        echo -e "${locale} has a new_loc"
    fi
fi

any ideas on how otherwise I can test for this?


Solution

  • I managed to solve the problem by checking if the variable is not an empty string instead.

    Example:

    locale=fr_ma
    declare -A new_loc
    new_loc[fr_ma]=en_ma
    new_loc[el_gr]=en_gr
    
    if [[ ! -z ${new_loc[$locale]} ]]; then
        echo "Locale ${locale} now maps to ${new_loc[$locale]}"
    fi
    

    Output:

    Locale fr_ma now maps to en_ma