How can i populate an array in loop? I’d like to do something like that:
declare -A results
results["a"]=1
results["b"]=2
while read data; do
results[$data]=1
done
for i in "${!results[@]}"
do
echo "key : $i"
echo "value: ${results[$i]}"
done
But it seems that I cannot add anything to an array within for loop. Why?
What you have should work, assuming you have a version of Bash that supports associative arrays to begin with.
If I may take a wild guess . . . are you running something like this:
? That is — is your
whileloop part of a pipeline? If so, then that‘s the problem. You see, every command in a pipeline receives a copy of the shell’s execution environment. So thewhileloop would be populating a copy of theresultsarray, and when thewhileloop completes, that copy disappears.Edited to add: If that is the problem, then as glenn jackman points out in a comment, you can fix it by using process substitution instead:
That way, although
command_that_outputs_keyswill receive only a copy of the shell’s execution environment (as before), thewhileloop will have the original, main environment, so it will be able to modify the original array.