#!/bin/bash
#M Network bandwidth monitor
#
# Written by George Toft
#
# This script displays the instantaneous data transfer on each network interface
# The data is updated each 5 seconds
#
# Written 02/01/07
# 
DEBUG=0 # 0=normal; 1=verbose
echo "Bandwidth Monitor. Written by George Toft."
echo "Collecting initial data . . ."
 
IFACES=( `cut -f1 -d: /proc/net/dev | egrep -v "Inter| face"` )
IFACE_NUM=$((${#IFACES[@]} - 1))
[ $DEBUG -gt 0 ] && echo "DEBUG: IFACES=$IFACES IFACE_NUM=$IFACE_NUM"
# Initialize tracking variables
for NICNUM in `seq 0 $IFACE_NUM`; do
    Tx[$NICNUM]=`grep ${IFACES[NICNUM]} /proc/net/dev | tr ":" " " | awk '{print $10}'`
    Rx[$NICNUM]=`grep ${IFACES[NICNUM]} /proc/net/dev | tr ":" " " | awk '{print $2}'`
    [ $DEBUG -gt 0 ] && echo "DEBUG: Tx[$NICNUM]=${Tx[NICNUM]} Rx[$NICNUM]=${Rx[NICNUM]}"
done
sleep 5
while true; do
    if [ $DEBUG -eq 0 ]; then
        clear
        printf " \t  Rx Bytes\t  Tx Bytes\n"
        printf "NIC \t  per sec\t  per sec\n"
        printf "====\t  ========\t  ========\n"
    fi
    for NICNUM in `seq 0 $IFACE_NUM`; do
        [ $DEBUG -gt 0 ] && echo "DEBUG: NICNUM=$NICNUM"
        T0=${Tx[NICNUM]}
        R0=${Rx[NICNUM]}
        [ $DEBUG -gt 0 ] && echo "DEBUG: T0=$T0 R0=$R0"
        Tx[$NICNUM]=`grep ${IFACES[NICNUM]} /proc/net/dev | tr ":" " " | awk '{print $10}'`
        Rx[$NICNUM]=`grep ${IFACES[NICNUM]} /proc/net/dev | tr ":" " " | awk '{print $2}'`
        [ $DEBUG -gt 0 ] && echo "DEBUG: Tx[$NICNUM]=${Tx[NICNUM]} Rx[$NICNUM]=${Rx[NICNUM]}"
        dTx=$((${Tx[NICNUM]} - $T0))
        dRx=$((${Rx[NICNUM]} - $R0))
        [ $DEBUG -gt 0 ] && echo "DEBUG: dTx=$dTx dRx=$dRx"
        RateTx=$(($dTx / 5)) 
        RateRx=$(($dRx / 5)) 
        [ $DEBUG -gt 0 ] && echo "DEBUG: RateTx=$RateTx RateRx=$RateRx"
        if [ $DEBUG -eq 0 ]; then
            printf "${IFACES[NICNUM]}\t"
            printf "%10d\t" $RateTx
            printf "%10d\n" $RateRx
        fi
        done
    sleep 5
done