Bash – Return the output of a command into an associative array

associative arraybashshell-script

I need to put the output of a command into an associative array.

For example:

dig mx +short google.com

Will return:

20 alt1.aspmx.l.google.com.
40 alt3.aspmx.l.google.com.
50 alt4.aspmx.l.google.com.
10 aspmx.l.google.com.
30 alt2.aspmx.l.google.com.

How can I create an associative array using the priorities (10,20,…) as the key and the record (aspmx.l.google.com.) as the value?

Best Answer

Here is one way to read that data into a bash associative array:

Code:

#!/usr/bin/env bash
declare -A hosts
while IFS=" " read -r priority host ; do
  hosts["$priority"]="$host"
done < <(dig mx +short google.com)    

for priority in "${!hosts[@]}" ; do
  echo "$priority -> ${hosts[$priority]}"
done

Output:

20 -> alt1.aspmx.l.google.com.
10 -> aspmx.l.google.com.
50 -> alt4.aspmx.l.google.com.
40 -> alt3.aspmx.l.google.com.
30 -> alt2.aspmx.l.google.com.
Related Question