Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over associative arrays in Bash

Based on an associative array in a Bash script, I need to iterate over it to get the key and value.

#!/bin/bash  declare -A array array[foo]=bar array[bar]=foo 

I actually don't understand how to get the key while using a for-in loop.

like image 963
pex Avatar asked Jun 24 '10 18:06

pex


People also ask

How do you iterate an associative array?

The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.

Does bash have associative arrays?

Bash, however, includes the ability to create associative arrays, and it treats these arrays the same as any other array. An associative array lets you create lists of key and value pairs, instead of just numbered values.

How do I sort an array in bash?

Bubble sort works by swapping the adjacent elements if they are in the wrong order. Example: Given array - (9, 7, 2, 5) After first iteration - (7, 2, 5, 9) After second iteration - (2, 5, 7, 9) and so on... In this way, the array is sorted by placing the greater element at the end of the array.

How can we define an associative array and assign a value to it?

Definition and Usage In PHP, an array is a comma separated collection of key => value pairs. Such an array is called Associative Array where value is associated to a unique key. The key part has to ba a string or integer, whereas value can be of any type, even another array. Use of key is optional.


1 Answers

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

You can iterate over the key/value pairs like this:

for i in "${!array[@]}" do   echo "key  : $i"   echo "value: ${array[$i]}" done 

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.

like image 108
Dennis Williamson Avatar answered Sep 18 '22 08:09

Dennis Williamson