arrays – bash:如何更新隐式子shell中的关联数组?
发布时间:2020-12-15 18:19:52 所属栏目:安全 来源:网络整理
导读:问题:我无法在while循环中更新数组.插图(不是实际问题): declare -A wordcountswordcounts["sentinel"]=1000ls *.txt | while read f; do # assume that that loop runs multiple times wordcounts[$f]=$(wc -w $f) echo ${wordcounts[$f]} # this prints
问题:我无法在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' 这不起作用,因为管道在子shell中运行后循环.循环对可变字数的所有更改仅在循环内可见. 说导出wordcounts没有帮助. 唉,我似乎需要管道和while读取部分,所以使用for重写上面代码的方法并不是我想要的. 有没有合法的方法来更新循环中的关联数组形式,或者一般的子shell? 解决方法
由于您有一个复杂的命令管道,您可以使用以下内容:
while read f; do # Do stuff done < <(my | complex | command | pipe) 语法<(command)在子shell中运行命令并将其stdout作为临时文件打开.您可以在通常在命令中使用文件的任何位置使用它. 此外,您还可以使用语法>(命令)将stdin作为文件打开. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |