bash:如何更新隐式子shell中的关联数组?

900*_*000 6 arrays bash loops associative-array subshell

问题:我无法在while循环中更新数组.插图(不是实际问题):

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'
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为管道在子shell中运行后循环.循环对变量所做的所有更改wordcounts仅在循环内可见.

export wordcounts没有用.

唉,我似乎需要管道while read部件,所以重写上面的代码的方法for并不是我想要的.

有没有合法的方法来更新循环中的关联数组形式,或者一般的子shell?

Coo*_*kyt 7

由于您有一个复杂的命令管道,您可以使用以下内容:

while read f; do
    # Do stuff
done < <(my | complex | command | pipe)
Run Code Online (Sandbox Code Playgroud)

语法<(command)在子shell中运行命令并将其stdout作为临时文件打开.您可以在通常在命令中使用文件的任何位置使用它.

此外,您还可以使用语法>(command)将stdin作为文件打开.