退出循环后为什么我的数组会消失?

时间:2012-10-26 17:35:34

标签: bash

  

可能重复:
  Bash: can’t build array in right side of pipe

我需要从文件创建一个数组。我必须计算存储数据的索引。当我进入读取循环外,我的数组似乎消失了。为什么???

下面的脚本说明了问题。

#!/bin/bash

echo -e "15\n21\n33" | while read i ; do
    ar[$i]="set"
    echo ${!ar[@]}
    echo ${ar[@]}
  done

echo
echo outside loop:  
echo ${!ar[@]} 
echo ${ar[@]} 

正如您在输出中看到的那样,打印数组索引和内容不再在循环外工作。

15
set
15 21
set set
15 21 33
set set set

outside loop:

1 个答案:

答案 0 :(得分:5)

@ormaaj在他的评论中有答案:不要把循环放在管道中。我假设这些数字不是常数,所以改为从流程替换重定向:

while read i ; do
    ar[$i]="set"
    echo ${!ar[@]}
    echo ${ar[@]}
done < <(process to generate indices) 

另一种选择是将最终的echo语句放在与循环相同的子shell中:

process to generate indices | {
    while read i ; do
        ar[$i]="set"
        echo ${!ar[@]}
        echo ${ar[@]}
    done

    echo
    echo outside loop:  
    echo ${!ar[@]} 
    echo ${ar[@]} 
}
相关问题