Skip to content

Instantly share code, notes, and snippets.

@cjsewell
Forked from radu-gheorghe/traffic.sh
Last active October 16, 2023 09:51
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cjsewell/96463db7fec6faeab291 to your computer and use it in GitHub Desktop.
Save cjsewell/96463db7fec6faeab291 to your computer and use it in GitHub Desktop.
#!/bin/bash
#shows traffic on the specified device
function human_readable {
VALUE=$1
BIGGIFIERS=( B K M G )
CURRENT_BIGGIFIER=0
while [ $VALUE -gt 10000 ] ;do
VALUE=$(($VALUE/1000))
CURRENT_BIGGIFIER=$((CURRENT_BIGGIFIER+1))
done
#echo "value: $VALUE"
#echo "biggifier: ${BIGGIFIERS[$CURRENT_BIGGIFIER]}"
echo "$VALUE${BIGGIFIERS[$CURRENT_BIGGIFIER]}"
}
###CHECKS####
DEVICE=$1
IS_GOOD=0
for GOOD_DEVICE in `grep ":" /proc/net/dev | awk '{print $1}' | sed s/:.*//`; do
if [ "$DEVICE" = "$GOOD_DEVICE" ]; then
IS_GOOD=1
break
fi
done
if [ $IS_GOOD -eq 0 ]; then
echo "Device $DEVICE not found. Should be one of these:"
grep ":" /proc/net/dev | awk '{print $1}' | sed s/:.*//
exit 1
fi
###REAL STUFF
LINE=`grep $1 /proc/net/dev | sed s/.*://`;
RECEIVED=`echo $LINE | awk '{print $1}'`
TRANSMITTED=`echo $LINE | awk '{print $9}'`
TOTAL=$(($RECEIVED+$TRANSMITTED))
echo "Transmitted: `human_readable $TRANSMITTED`"
echo "Received: `human_readable $RECEIVED`"
echo "Total: `human_readable $TOTAL`"
SLP=3
echo "Sleeping $SLP to calculate speed..."
sleep $SLP
LINE=`grep $1 /proc/net/dev | sed s/.*://`;
RECEIVED=`echo $LINE | awk '{print $1}'`
TRANSMITTED=`echo $LINE | awk '{print $9}'`
SPEED=$((($RECEIVED+$TRANSMITTED-$TOTAL)/$SLP))
echo "Current speed: `human_readable $SPEED`/s"
@dagelf
Copy link

dagelf commented May 23, 2018

Added formatting, up/down/total throughput and made it embedded-compatible: https://gist.github.com/dagelf/ab2bad26ce96fa8d79b0834cd8cab549

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment