How to Sort an Associative Array in Bash (With Examples)


Often you may want to sort an associative array in Bash.

You can use the following methods to do so:

Method 1: Sort Associative Array by Key

for k in "${!my_array[@]}"
do
    echo $k ' - ' ${my_array["$k"]}
done |
sort | xargs -n3

This particular example will sort the associative array named my_array based on the keys.

Method 2: Sort Associative Array by Value

for k in "${!my_array[@]}"
do
    echo $k ' - ' ${my_array["$k"]}
done |
sort -nr -k3

This particular example will sort the associative array named my_array based on the values.

Note: In this example we specify sort -nr to sort the values in numerical reverse order.

The following example shows how to use each of these methods in practice with the following associative array named my_array in which the keys are the names of basketball teams and the values are points scored by a player on that team:

declare -A my_array=( [Mavs]=22 [Heat]=14 [Nets]=36 [Hawks]=29 )

Example 1: Sort Associative Array by Key

We can use the following syntax to sort the associative array named my_array based on the keys of the array:

for k in "${!my_array[@]}"
do
    echo $k ' - ' ${my_array["$k"]}
done |
sort | xargs -n3

The following screenshot shows how to use this syntax in practice:

Bash sort associative array by keys

Notice that this returns the associate array sorted in order based on the keys in alphabetical order:

  • Hawks
  • Heat
  • Mavs
  • Nets

Example 2: Sort Associative Array by Value

We can use the following syntax to sort the associative array named my_array based on the keys of the array:

for k in "${!my_array[@]}"
do
    echo $k ' - ' ${my_array["$k"]}
done |
sort -nr -k3

The following screenshot shows how to use this syntax in practice:

Bash sort associative array by values

Notice that this returns the associate array sorted in order based on the values in descending numerical order:

  • 36
  • 29
  • 22
  • 14

Note: You can use sort -n -k3 on the last line to instead sort based on values in ascending order.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Iterate Over Associative Array
Bash: How to Split a String into an Array
Bash: How to Remove Last Element from Array
Bash: How to Find Minimum and Maximum Values in Array

Leave a Reply