Grug
Grug

Reputation: 1890

Split output of command into an associative array in bash

The output is

/     ext4
/boot ext2
tank  zfs

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

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

How is this done in bash?

Upvotes: 11

Views: 5580

Answers (1)

John1024
John1024

Reputation: 113994

If the command output is in file file, then:

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

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

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

The construct <(...) is process substitution. It allows us to read from a command the same as if we were reading from a file. Note that the space between the two < is essential.

You can verify that the data was read correctly using declare -p:

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

Upvotes: 19

Related Questions