Variable loss in redirected bash while loop

Posted by James Hadley on Stack Overflow See other posts from Stack Overflow or by James Hadley
Published on 2013-10-20T13:54:21Z Indexed on 2013/10/20 15:54 UTC
Read the original article Hit count: 198

I have the following code

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

Which I would like to print the incremented values to bwacct.txt, but instead the file is full of zeroes:

91.227.223.66 0 0
91.227.221.126 0 0
127.0.0.1 0 0

My understanding of Bash is that a redirected for loop should preserve variables. What am I doing wrong?

© Stack Overflow or respective owner

Related posts about bash

Related posts about while-loop