blob: ead10fd99be957ff2a27d7368e2ca21fe76babb1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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")"
|