This is the second mini tutorial about Associative Arrays in Bash. You can check the previous one here:
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.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
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.
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:
As we said, we’ll be accessing elements of an associative array by using 2 different methods:
Access elements Individually
You can access values in an associative array by calling it’s key:
in our case
The output will be Berlin:
We can even ECHO all VALUES or KEYS in the array like so:
echo all VALUES:
echo all KEYS:
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.
Now, similar to the previous point, we can call all KEYS using the exclamation symbol (!) before the name of the array -
Next time we’ll be reviewing how to use WHILE loops with Associative arrays in BASH and what to use them for.