shell数组赋值失败问题

编写了一个shell脚本,发现数组赋值失败,原代码:

monthDate=$1
logBaseHome=/data/mqq_data/log_center/
rootHome=/data/mqq_data/log_center/silly/tools/dolphinInfo/


result=(0 0 0 0 0 0 0 0)
fileName=$rootHome/$monthDate"."monthUsersInfo.data
cat $fileName | while read line 
do
    num=`echo $line |awk '{print $2}'`
    if [ $num -gt 0 -a $num -le 20 ]; then
       let result[0]+=1
    elif [ $num -gt 20 -a $num -le 50 ]; then
       let result[1]+=1
    elif [ $num -gt 50 -a $num -le 200 ]; then
       let result[2]+=1
    elif [  $num -gt 200 -a $num -le 1000 ]; then
       let result[3]+=1
    elif [ $num -gt 1000 -a $num -le 3000 ]; then
       let result[4]+=1
    elif [ $num -gt 3000 -a $num -le 6000 ]; then
       let result[5]+=1
    elif [ $num -gt 6000 -a $num -le 8000 ]; then
       let result[6]+=1
    elif [ $num -gt 8000 ]; then
       let result[7]+=1
    fi

    #echo ${result[*]}
done
echo ${result[*]}

发现不论如何result在循环里修改都没有用
原因:
    管道中的while是在子shell中运行的,并不能返回到父shell中

修改:

 monthDate=$1
logBaseHome=/data/mqq_data/log_center/
rootHome=/data/mqq_data/log_center/silly/tools/dolphinInfo/


result=(0 0 0 0 0 0 0 0)
fileName=$rootHome/$monthDate"."monthUsersInfo.data
while read line 
do
    num=`echo $line |awk '{print $2}'`
    if [ $num -gt 0 -a $num -le 20 ]; then
       let result[0]+=1
    elif [ $num -gt 20 -a $num -le 50 ]; then
       let result[1]+=1
    elif [ $num -gt 50 -a $num -le 200 ]; then
       let result[2]+=1
    elif [  $num -gt 200 -a $num -le 1000 ]; then
       let result[3]+=1
    elif [ $num -gt 1000 -a $num -le 3000 ]; then
       let result[4]+=1
    elif [ $num -gt 3000 -a $num -le 6000 ]; then
       let result[5]+=1
    elif [ $num -gt 6000 -a $num -le 8000 ]; then
       let result[6]+=1
    elif [ $num -gt 8000 ]; then
       let result[7]+=1
    fi

    #echo ${result[*]}
done<$fileName
echo ${result[*]}
问题解决


你可能感兴趣的:(Shell,StudyNotes,shell,数组,赋值,失败)