bash 在循环中填充数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9985076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:56:35  来源:igfitidea点击:

bash populate an array in loop

bashfor-loopassociative-array

提问by Dejwi

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?

但似乎我无法在 for 循环中向数组添加任何内容。为什么?

回答by ruakh

What you have should work, assuming you have a version of Bash that supports associative arrays to begin with.

假设您有一个支持关联数组的 Bash 版本,那么您所拥有的应该可以工作。

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 whileloop part of a pipeline? If so, then that's the problem. You see, every command in a pipeline receives a copyof the shell's execution environment. So the whileloop would be populating a copyof the resultsarray, and when the whileloop completes, that copy disappears.

? 也就是说——你的while循环是管道的一部分吗?如果是这样,那就是问题所在。您会看到,管道中的每个命令都会收到shell 执行环境的副本。所以while循环会填充一个副本中的results阵列,而当while循环完成,该副本消失。

Edited to add:If that isthe problem, then as glenn Hymanmanpoints out in a comment, you can fix it by using process substitutioninstead:

编辑添加:如果这问题所在,那么正如glenn Hymanman在评论中指出的那样,您可以使用进程替换来修复它:

while read data; do
    results[$data]=1
done < <(command_that_outputs_keys)

That way, although command_that_outputs_keyswill receive only a copy the shell's execution environment (as before), the whileloop will have the original, main environment, so can modify the original array.

这样,虽然command_that_outputs_keys只会收到一个 shell 执行环境的副本(和以前一样),但while循环将拥有原始的主环境,因此可以修改原始数组。

回答by icyrock.com

That seems to be working fine:

这似乎工作正常:

$ cat mkt.sh 
declare -A results

results["a"]=1
results["b"]=2

while read data; do
  results[$data]=1
done << EOF
3
4
5
EOF

for i in "${!results[@]}"
do
  echo "key  : $i"
  echo "value: ${results[$i]}"
done

$ ./mkt.sh 
key  : a
value: 1
key  : b
value: 2
key  : 3
value: 1
key  : 4
value: 1
key  : 5
value: 1
$ 

Ubuntu 11.10 here, bash: GNU bash, version 4.2.10(1)-release (x86_64-pc-linux-gnu).

这里是 Ubuntu 11.10,bash:GNU bash,版本 4.2.10(1)-release (x86_64-pc-linux-gnu)。