我有以下代码
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循环应该保留变量。我做错了什么?
答案 0 :(得分:2)
首先,简化您的脚本!通常在bash中有许多更好的方法。大多数情况下,您可以依赖纯粹的bash解决方案,而不是运行awk或其他工具 然后添加一些debbuging! 这是一个带有调试的位重构脚本
#!/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
现在更清楚了,是吗? :)