By KFSys
System Administrator
Hi all,
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!
Accepted 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
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.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.