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?
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" )'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With