The problem: I cannot update an array in a while
loop. An illustration (not the actual problem):
declare -A wordcounts
wordcounts["sentinel"]=1000
ls *.txt | while read f; do
# assume that that loop runs multiple times
wordcounts[$f]=$(wc -w $f)
echo ${wordcounts[$f]} # this prints actual data
done
echo ${!wordcounts[@]} # only prints 'sentinel'
This does not work, because the loop after the pipe runs in a subshell. All the changes that the loop does to variable wordcounts
are only visible inside the loop.
Saying export wordcounts
does not help.
Alas, I seem to need the pipe and the while read
part, so ways to rewrite the code above using for
is not what I'm looking for.
Is there a legitimate way to update an associative array form within a loop, or a subshell in general?