Show Real-time Net Speed

Posted on Thu 21 February 2019 in coding


Show net speed in dwm's status bar.

Original code

kai hendry's version

My code of real-time net speed

The procedure

  1. get download/upload bytes at a timepoint
  2. get the bytes after 1 second
  3. calculate speed

The final code


get_ninfo() {
    # get network info: rx bytes & tx bytes at a timepoint
    # (rx, tx, tp) in $ninfo, as a list

    interface=`ip ro g 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

while ((1)) {
    nspd $ninfo $old_ninfo
    sleep 1

Details to cater to

  • copy array
    Use arr1_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