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).

Initialize an empty associative array:
# Remember, key/value array is only available in Bash +4.0.
declare -A locale_array
Add or modify elements in the array:
# One element.
locale_array["English (Canada)"]=en_CA

# Or many elements at the same time.
  ["English (UK)"]=en_UK
  ["English (USA)"]=en_US
Get array length (note the hash at the beginning):
$ echo "${#locale_array[@]}"
Access keys (note the exclamation mark at the beginning):
$ echo "${!locale_array[@]}"
English (USA) English (Canada) English (UK)
Access values:
# One value.
$ echo "${locale_array[English (USA)]}"

# All values.
$ echo "${locale_array[@]}"
en_US en_CA en_UK
Loop over the array:
# Loop over the array.
$ for key in "${!locale_array[@]}"; do
    echo "- ${key} => ${locale_array[$key]}";

- English (USA)    => en_US
- English (Canada) => en_CA
- English (UK)     => en_UK
Remove an element from the array:
unset locale_array["English (UK)"]
These were most common operations for arrays. Simple and easy! Thanks for Bash 4!
Powered by Blogger.

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

I'm a passionate DevOps engineer, Cloud/Kubernetes specialist, Free/Open source geek, and an author.

I believe in self CI/CD (Continuous Improvements/Development), also that "the whole is greater than the sum of its parts".

DevOps transformation, automation, data, and metrics are my preferred areas. And I like to help both businesses and people to grow.

Latest Post

🔀Merger🔀, a schemaless strategic merge plugin - Kustomize

Kustomize is a great tool. I've been using Kustomize for almost 4 years and am happy with it. However, it's ...

Popular Posts