Interface Stats

Sometime you just wanna check how many packets and bytes are transferred via network interface. For my Linode NTP server I solved that need using the following script:

#!/bin/bash

INTERFACE=eth0

LINE_COUNT=`tput lines`
LINE=-1

while true
do
    if (( LINE % (LINE_COUNT-1) == 0 ))
    then
        echo "INTERFACE   RX bytes packets     TX bytes packets"
    fi
    LINE=$(( LINE+1 ))

    RX1_BYTES=$RX2_BYTES
    TX1_BYTES=$TX2_BYTES
    RX1_PACKETS=$RX2_PACKETS
    TX1_PACKETS=$TX2_PACKETS
    sleep 1
    RX2_BYTES=`cat /sys/class/net/$INTERFACE/statistics/rx_bytes`
    TX2_BYTES=`cat /sys/class/net/$INTERFACE/statistics/tx_bytes`
    RX2_PACKETS=`cat /sys/class/net/$INTERFACE/statistics/rx_packets`
    TX2_PACKETS=`cat /sys/class/net/$INTERFACE/statistics/tx_packets`

    if [[ "$RX1_BYTES" != "" ]]
    then
        RX_BYTES=$(( RX2_BYTES - RX1_BYTES ))
        TX_BYTES=$(( TX2_BYTES - TX1_BYTES ))
        RX_PACKETS=$(( RX2_PACKETS - RX1_PACKETS ))
        TX_PACKETS=$(( TX2_PACKETS - TX1_PACKETS ))

        printf "%-7s  %'11d %'7d  %'11d %'7d\n" $INTERFACE $RX_BYTES $RX_PACKETS $TX_BYTES $TX_PACKETS
    fi
done