Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split output of command into an associative array in bash

Tags:

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?

like image 919
drack Avatar asked May 30 '15 01:05

drack


1 Answers

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" )'
like image 183
John1024 Avatar answered Sep 29 '22 12:09

John1024