Show Real-time Net Speed
Posted on Thu 21 February 2019 in coding
Effect
Show net speed in dwm's status bar.
Original code
My code of real-time net speed
The procedure
- get download/upload bytes at a timepoint
- get the bytes after 1 second
- calculate speed
The final code
#!/bin/zsh
get_ninfo() {
# get network info: rx bytes & tx bytes at a timepoint
# (rx, tx, tp) in $ninfo, as a list
interface=`ip ro g 1.1.1.1 2>/dev/null | awk '{print $5}'` # active network interface
ninfo=(`awk -v p=$interface '$0 ~ p {print $2, $10}' /proc/net/dev`)
ninfo+=`date +%s%N` # nanosec
}
nspd() {
# calc rx/tx (down/up) net speed
deltat=$((($3-$6)/1e9)) # sec
spd=(`numfmt --to=iec $((($1 - $4)/$deltat)) $((($2 - $5)/$deltat))`)
echo $spd[1]B/s $spd[2]B/s
}
get_ninfo
old_ninfo=($ninfo)
while ((1)) {
get_ninfo
nspd $ninfo $old_ninfo
old_ninfo=($ninfo)
sleep 1
}
Details to cater to
-
copy array
Usearr1_dup=($arr1)
,
not
...arr1_dup=$arr1
see this -
math calc in shell script
see here -
precise time gap
use nanosecond (%N
) as unit for time gap -
zsh (-friendly) style
function, loop control