#!/usr/bin/env bash set -euo pipefail iface="${POLYBAR_NETWORK:-eth0}" state_dir="${XDG_RUNTIME_DIR:-/tmp}" if [ ! -w "$state_dir" ]; then state_dir="${XDG_CACHE_HOME:-$HOME/.cache}" mkdir -p "$state_dir" fi if [ ! -w "$state_dir" ]; then state_dir="/tmp" fi state_file="$state_dir/polybar-net-${iface}.state" rx_file="/sys/class/net/$iface/statistics/rx_bytes" tx_file="/sys/class/net/$iface/statistics/tx_bytes" human() { local bytes="$1" if [ "$bytes" -ge 1048576 ]; then awk -v v="$bytes" 'BEGIN { printf "%.1fM", v / 1048576 }' elif [ "$bytes" -ge 1024 ]; then awk -v v="$bytes" 'BEGIN { printf "%.0fK", v / 1024 }' else printf '%sB' "$bytes" fi } if [ ! -r "$rx_file" ] || [ ! -r "$tx_file" ]; then echo "n/a" exit 0 fi now="$(date +%s)" rx="$(cat "$rx_file")" tx="$(cat "$tx_file")" if [ -r "$state_file" ]; then read -r old_now old_rx old_tx <"$state_file" || true else old_now="$now" old_rx="$rx" old_tx="$tx" fi printf '%s %s %s\n' "$now" "$rx" "$tx" >"$state_file" delta=$((now - old_now)) if [ "$delta" -le 0 ]; then delta=1 fi down=$(((rx - old_rx) / delta)) up=$(((tx - old_tx) / delta)) if [ "$down" -lt 0 ]; then down=0 fi if [ "$up" -lt 0 ]; then up=0 fi printf '%s/%s\n' "$(human "$down")" "$(human "$up")"