bash populate an array in loop
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:
command_that_outputs_keys \
| while read data; do
results[$data]=1
done
? That is — is your while
loop 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 the while
loop would be populating a copy of the results
array, and when the while
loop 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:
while read data; do
results[$data]=1
done < <(command_that_outputs_keys)
That way, although command_that_outputs_keys
will receive only a copy of the shell's execution environment (as before), the while
loop will have the original, main environment, so it will be able to modify the original array.