Key value array in shell scripts! - Bash

I really believe if you need key-value (aka associative array) in your script, then you need to move to a real language which most probably will be Python or so.

But for some reasons, you maybe need it in one of your bash scripts. And of course will not rewrite the script just for that part! So you can use key-value array (And of course instead old tricks like using delimiter inside each value).

So, here how to make key-value array in Bash v4 (which comes with most Linux systems nowadays).

# Key value array is only available in Bash +4.0
declare -A localeArray

# Set key value.
  ["English (Canada)"]=en_CA
  ["English (UK)"]=en_UK
  ["English (USA)"]=en_US

# To get value of any element.
$ echo "${localeArray[English (USA)]}"

# To access keys (note the exclamation mark at the beginning).
$ printf -- "- %s\n" "${!localeArray[@]}"
- English (USA)
- English (Canada)
- English (UK)

# To access values.
$ printf -- "- %s\n" "${localeArray[@]}"
- en_US
- en_CA
- en_UK

# Loop over the array.
$ for key in "${!localeArray[@]}"; do
    echo "- ${key} => ${localeArray[$key]}";
- English (USA)    => en_US
- English (Canada) => en_CA
- English (UK)     => en_UK
Powered by Blogger.

Hello, my name is Ahmed AbouZaid and this is my "lite" technical blog!

I'm a passionate DevOps, Linux system engineer, RHCE, AWS SysOps/Solutions Architect, Free/Open source geek, author, interested in environment, calligraphy, and I believe that “Details Matter”!

Automation, data, and metrics are my preferred areas. I have a built-in monitoring chip, and too lazy to do anything manually :D

Popular Posts