ambevar-dotfiles/.scripts/netspeed

52 lines
1.3 KiB
Bash
Executable File

#!/bin/sh
if [ "$1" = "-h" ] || [ $# -gt 1 ]; then
cat<<EOF
Usage: ${0##*/} [INTERFACE]
Return up and down transmission speed on given interface. If not given, use the
first online interface returned by ifconfig (lo is ignored).
EOF
exit
fi
if [ -n "$1" ]; then
interface="$1"
else
interface="$(ifconfig | grep -vm1 '^lo\|^ \|^$' | cut -f1 -d':')"
## AWK alternative
# ifconfig | awk -F: '!/^ / && !/^$/ && $1!="lo" {print $1;exit}'
fi
if [ ! -d "/sys/class/net/${interface}" ]; then
echo "Error: no such interface: ${interface}" >&2
else
path="/dev/shm/netspeed"
time=$(date +%s)
read rx < /sys/class/net/${interface}/statistics/rx_bytes
read tx < /sys/class/net/${interface}/statistics/tx_bytes
if [ ! -f "$path" ]; then
echo "$time $rx $tx" > "$path"
chmod 0666 "$path"
fi
read time_old rx_old tx_old < "$path"
echo "$time $rx $tx" > "$path"
time_diff=$(($time - $time_old))
if [ "$time_diff" -gt 0 ]; then
rx_rate=$((($rx - $rx_old) / $time_diff))
tx_rate=$((($tx - $tx_old) / $time_diff))
[ "$rx_rate" -gt 1024 ] && rx_rate=$(($rx_rate / 1024)) && rx_unit=K
[ "$rx_rate" -gt 1024 ] && rx_rate=$(($rx_rate / 1024)) && rx_unit=M
[ "$tx_rate" -gt 1024 ] && tx_rate=$(($tx_rate / 1024)) && tx_unit=K
[ "$tx_rate" -gt 1024 ] && tx_rate=$(($tx_rate / 1024)) && tx_unit=M
echo -n "$rx_rate $rx_unit$tx_rate $tx_unit"
fi
fi