23/07/2016

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.
locale_array+=(
  ["English (UK)"]=en_UK
  ["English (USA)"]=en_US
)
Get array length (note the hash at the beginning):
$ echo "${#locale_array[@]}"
3
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)]}"
en_US

# 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]}";
done

- 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 short feedback loops help create better software.

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

Popular Posts