如何在bash中使用全局数组?

我正在通过search和谷歌find解决我的问题2天,但我没有运气。 我的问题是,我有一个数组,我用0开始它的元素,并且我修改了它的元素值在\ while循环范围内。 但是当我在循环外打印数组的值时,我发现它们都是0的初始值!

这是我的代码:

#!/bin/bash # # This is a script to reformat CSV files into pretty-formatted txt files. clear echo 'This is a script to reformat CSV files into pretty-formatted txt files.' echo # Get number of elements. elements=$(cat CSV_File | sed -n 1'p' | tr ',' '\n' | wc -l) # "cat CSV_File" for getting text of the file. # "sed -n 1'p'" for getting only first line. # "tr ',' '\n'" for replacing ',' with '\n'. # "wc -l" for getting number of lines (ie number of elements). # Get number of lines. lines=$(cat CSV_File | wc -l) # "cat CSV_File" for getting text of the file. # "wc -l" for getting number of lines. # Initiate an array for elements' lengths. for ((i=1; $i < (( $elements + 1 )) ;i++)) do lengths[$i]="0" done # Find tallest element of each column and put the values into 'lengths' array. for ((i=1; $i <= $lines ;i++)) do j="1" cat CSV_File | sed -n ${i}'p' | tr ',' '\n' | while read element do if [ ${lengths[$j]} -le ${#element} ] then lengths[$j]=${#element} fi (( j++ )) done done echo ${lengths[1]} # It should print 5 not 0 echo ${lengths[2]} # It should print 4 not 0 echo ${lengths[3]} # It should print 19 not 0 echo ${lengths[4]} # It should print 11 not 0 echo ${lengths[5]} # It should print 2 not 0 echo ${lengths[6]} # It should print 5 not 0 echo ${lengths[7]} # It should print 14 not 0 echo ... 

这里是CSV_File的内容:

 Jones,Bill,235 S. Williams St.,Denver,CO,80221,(303) 244-7989 Smith,Tom,404 Polk Ave.,Los Angeles,CA,90003,(213) 879-5612 

请注意,当我把echo里面的if语句,它打印正确的值:

 if [ ${lengths[$j]} -le ${#element} ] then lengths[$j]=${#element} echo ${lengths[$j]} fi 

我在做什么错 我错过了什么吗?

Solutions Collecting From Web of "如何在bash中使用全局数组?"

| while read element; do ... done | while read element; do ... done | while read element; do ... done在子shell中运行,所以当子shell退出时,其全局更新将丢失。

一种解决方案是使用bash的“进程替换”来获得输入到while循环而不是在子shell中运行。 请参阅: 在bash中读取多行而不产生新的子shell?