diff options
| author | David Moc <personal@cdatgoose.org> | 2026-05-24 11:48:07 +0200 |
|---|---|---|
| committer | David Moc <personal@cdatgoose.org> | 2026-05-24 11:48:07 +0200 |
| commit | 5fb19f10389b70ee2389755106092a9ef6c64598 (patch) | |
| tree | 969eb0466de581cb14aa09f751a95138620fc720 /polybar/scripts/net-speed.sh | |
Go
Diffstat (limited to 'polybar/scripts/net-speed.sh')
| -rwxr-xr-x | polybar/scripts/net-speed.sh | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/polybar/scripts/net-speed.sh b/polybar/scripts/net-speed.sh new file mode 100755 index 0000000..ead10fd --- /dev/null +++ b/polybar/scripts/net-speed.sh @@ -0,0 +1,64 @@ +#!/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")" |
