【问题标题】:How to use global arrays in bash?如何在 bash 中使用全局数组?
【发布时间】:2011-10-13 17:43:18
【问题描述】:

我在 SO 和 google 中搜索了 2 天来解决我的问题,但我没有运气。我的问题是我有一个数组,我用 0 初始化它的元素,然后在 for\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 (i.e 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

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

【问题讨论】:

    标签: linux bash shell ubuntu


    【解决方案1】:

    | while read element; do ... done 在子 shell 中运行,因此当子 shell 退出时,它对全局的更新会丢失。

    一种解决方案是使用 bash 的“进程替换”来获取 while 循环的输入,以便在子 shell 中运行。看: Reading multiple lines in bash without spawning a new subshell?

    【讨论】:

    • 非常感谢您的解释和链接,它为我节省了很多时间并澄清了我的问题
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多