Question

Associative Arrays in Bash - Accessing Elements in an Associative array

Posted May 11, 2021 448 views
Linux BasicsLinux Commands

Hi all,

This is the second mini tutorial about Associative Arrays in Bash. You can check the previous one here:

https://www.digitalocean.com/community/questions/what-is-an-assosiative-array-and-can-it-be-used-in-bash-part-1

In this mini-tutorial, we’ll be talking about how to access elements in an associative array. We’ll be accessing them individually with for loops.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Following the example from the previous part, we’ll create an Associative array called DOAssosArray and populate it with Counties as keys and Capitals as values:

declare -A DOAssosArray
DOAssosArray[Germany]=Berlin
DOAssosArray[France]=Paris
DOAssosArray[Spain]=Madrid

As we said, we’ll be accessing elements of an associative array by using 2 different methods:

  • Access elements Individually
  • Access elements with a for loop

Access elements Individually

You can access values in an associative array by calling it’s key:

echo ${DOAssosArray[KEY]}

in our case

echo ${DOAssosArray[Germany]}

The output will be Berlin:

root@DevServer:~$ echo ${DOAssosArray[Germany]}
Berlin                

We can even ECHO all VALUES or KEYS in the array like so:

echo all VALUES:

root@nDevServer:~$ echo ${DOAssosArray[@]}
Madrid Berlin Paris

echo all KEYS:

root@nDevServer:~$ echo ${!DOAssosArray[@]}
Spain Germany France

Access elements with a for loop

Let’s say we need to print all values of an associative array, we’ll do that with a for loop.

for capitol in "${DOAssosArray[@]}"; do echo $capitol;done

Output:

root@DevServer:~$ for capitol in "${DOAssosArray[@]}"; do echo $capitol;done
Madrid
Berlin
Paris

Now, similar to the previous point, we can call all KEYS using the exclamation symbol (!) before the name of the array -

for country in "${!DOAssosArray[@]}"; do echo $country;done

Output:

root@DevServer:~$ for country in "${!DOAssosArray[@]}"; do echo $country;done
Spain
Germany
France

Next time we’ll be reviewing how to use WHILE loops with Associative arrays in BASH and what to use them for.