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, I'm a passionate Tech Lead DevOps Engineer. 👋

With 16+ years of open-source contributions, 12+ years of professional hands-on experience in DevOps, and an M.Sc. in Data Engineering from Edinburgh Napier University (UK), I enjoy facilitating the growth of both businesses and individuals.

I specialize in Cloud-Native and Kubernetes. I'm also a Free/Open source geek and book author. My favorite topics are DevOps transformation, automation, data, and metrics.

Contact Me

Name

Email *

Message *

Start Your DevOps Engineer Journey!

Start Your DevOps Engineer Journey!
Start your DevOps career for free the Agile way in 2024 with the Dynamic DevOps Roadmap ⭐

Latest Post

2023 Highlights

Image generated with Craiyon . Finally, 2023 is over! What a year! One more crazy year, but it was the culmination ...

Popular Posts

Blog Archive