Split command output into associative array in bash

Output signal

/ ext4 /boot ext2 tank zfs 

On each line, the separator is a space. I need an associative array like:

 "/" => "ext4", "/boot" => "ext2", "tank" => "zfs" 

How is this done in bash?

+8
bash
source share
1 answer

If the command output is in the file file , then:

 $ declare -A arr=(); while read -rab; do arr["$a"]="$b"; done <file 

Or you can read the data directly from the cmd command into an array as follows:

 $ declare -A arr=(); while read -rab; do arr["$a"]="$b"; done < <(cmd) 

The <(...) construct is a replacement for the process. This allows us to read from a command as if we were reading from a file. Note that the space between the two < significant.

You can verify that the data is read correctly with declare -p :

 $ declare -p arr declare -A arr='([tank]="zfs" [/]="ext4" [/boot]="ext2" )' 
+14
source share

All Articles