Associative array in bash not storing values inside loop [duplicate]
Asked Answered
E

1

8

This is my $a output:

[root@node1 ~]# echo "${a}"
/dev/vdc1 /gfs1
/dev/vdd1 /elastic
mfsmount /usr/local/flytxt

I gotta store these in an associative array fsmounts with first column as keys and second col as value.
This is my code for that:

declare -A fsmounts
echo "$a" | while read i ; do key=$(echo "$i" | awk '{print $1}'); value=$(echo "$i" | awk '{print $2}');fsmounts[$key]=$value;  done;

But when I try to print outside the loop with

[root@node1 ~]# echo ${fsmounts[/dev/vdb1]}

Blank is the output. I think the associative array fsmounts is not actually storing values. Please help me.

But I can actually able to echo fsmounts[$key] inside the loop. See this:

echo "$a" | while read i ; do key=$(echo "$i" | awk '{print $1}'); value=$(echo "$i" | awk '{print $2}');fsmounts[$key]=$value; echo ${fsmounts[$key]};  done;
/gfs1
/elastic
/usr/local/flytxt
Enchorial answered 7/2, 2019 at 6:9 Comment(0)
T
11

The imminent problem associated with your logic is I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?

You don't need awk or any third party tool at all for this. Just run it over a loop with a read and feed the string via standard input over the loop

declare -A fsmounts

while read -r key value; do
    fsmounts["$key"]="$value"
done <<<"$a"

now loop over the array with key and values

for key in "${!fsmounts[@]}"; do
    printf 'key=%s value=%s\n' "$key" "${fsmounts[$key]}"
done

More on how to use associative arrays - How can I use variable variables (indirect variables, pointers, references) or associative arrays?

Trifolium answered 7/2, 2019 at 6:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.