2

我有以下代码

for ip in $(ifconfig | awk -F ":"  '/inet addr/{split($2,a," ");print a[1]}')
do
    bytesin=0; bytesout=0;
    while read line
    do
        if [[ $(echo ${line} | awk '{print $1}') == ${ip} ]]
        then
            increment=$(echo ${line} | awk '{print $4}')
            bytesout=$((${bytesout} + ${increment}))
        else
            increment=$(echo ${line} | awk '{print $4}')
            bytesin=$((${bytesin} + ${increment}))
        fi
    done < <(pmacct -s | grep ${ip})
    echo "${ip} ${bytesin} ${bytesout}" >> /tmp/bwacct.txt
done

我想将增加的值打印到 bwacct.txt,但文件中充满了零:

91.227.223.66 0 0
91.227.221.126 0 0
127.0.0.1 0 0

我对 Bash 的理解是重定向的 for 循环应该保留变量。我究竟做错了什么?

4

1 回答 1

3

首先,简化你的脚本!通常在 bash 中有很多更好的方法。大多数时候,您可以依赖纯 bash 解决方案,而不是运行 awk 或其他工具。
然后添加一些调试!这是一个带有调试功能的重构脚本

#!/bin/bash
for ip in "$(ifconfig | grep -oP 'inet addr:\K[0-9.]+')"
do
    bytesin=0
    bytesout=0
    while read -r line
    do
        read -r subIp _ _ increment _ <<< "$line"
        if [[ $subIp == "$ip" ]]
        then
            ((bytesout+=increment))
        else
            ((bytesin+=increment))
        fi
        # some debugging
        echo "line: $line"
        echo "subIp: $subIp"
        echo "bytesin: $bytesin"
        echo "bytesout: $bytesout"
    done <<< "$(pmacct -s | grep "$ip")"
    echo "$ip $bytesin $bytesout" >> /tmp/bwacct.txt
done

现在清楚多了,是吧?:)

于 2013-10-20T15:45:04.560 回答