Skip to content

Instantly share code, notes, and snippets.

@cyrus-and
Last active March 13, 2016 15:31
Show Gist options
  • Save cyrus-and/8758472f6bf793230710 to your computer and use it in GitHub Desktop.
Save cyrus-and/8758472f6bf793230710 to your computer and use it in GitHub Desktop.
NIC stats from /sys/class/net/
#!/usr/bin/env bash
width=10
declare -a stats=(rx_bytes tx_bytes rx_packets tx_packets)
declare -a names=('RX Bps ' 'TX Bps' 'RX pps' 'TX pps')
declare -a fmt=('--to iec --suffix B' '--to iec --suffix B' '--to si' '--to si')
function get_stat() {
local iface="$1"
local stat="$2"
echo -n "$(< /sys/class/net/$iface/statistics/$stat)"
}
function get_all_stats() {
local iface="$1"
local values=()
shift
for stat; do
values+=("$(get_stat "$iface" "$stat")")
done
echo "${values[@]}"
}
function print_header() {
echo
for name; do
printf "%${width}s" "$name"
done
echo
echo
}
iface="${1:-lo}"
echo "# iface '$iface'" >&2
declare -a prev curr
n=0
prev=($(get_all_stats "$iface" "${stats[@]}"))
while sleep 1; do
if [ $((n % 10)) = 0 ]; then
print_header "${names[@]}" >&2
fi
curr=($(get_all_stats "$iface" "${stats[@]}"))
for (( i = 0 ; i < "${#stats[@]}" ; i++ )) ; do
metric=$((${curr[$i]} - ${prev[$i]}))
printf "%${width}s" "$(numfmt "$metric" ${fmt[$i]})"
done
echo
prev=("${curr[@]}")
n=$((n + 1))
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment