i3blocks-bandwidth: better support for varying magnitudes
authorAndrew Lorimer <andrew@lorimer.id.au>
Thu, 11 Oct 2018 05:16:28 +0000 (16:16 +1100)
committerAndrew Lorimer <andrew@lorimer.id.au>
Thu, 11 Oct 2018 05:16:28 +0000 (16:16 +1100)
a.k.a. bash arithmetic sucks

i3blocks-bandwidth.sh
index 26e5ac7ca656eea0d639db7da7f408162cced5cf..cab00a9eb9d8c064d32827d21947bbf76037337c 100755 (executable)
@@ -19,7 +19,7 @@
 # Get custom IN and OUT labels if provided by command line arguments
 while [[ $# -gt 1 ]]; do
     key="$1"
-    case "$key" in 
+    case "$key" in
         -i|--inlabel)
             INLABEL="$2"
             shift;;
@@ -90,7 +90,16 @@ tx_rate=$(( $tx_diff / $time_diff ))
 echo -n "$INLABEL"
 rx_kib=$(( $rx_rate >> 10 ))
 if hash bc 2>/dev/null && [[ "$rx_rate" -gt 1048576 ]]; then
-  printf '%sM' "`echo "scale=1; $rx_kib / 1024" | bc`"
+
+  if [ $rx_kib -lt 9900 ]; then
+    printf '%sM' "`echo "scale=1; $rx_kib / 1024" | bc`"
+  else
+    if [ $rx_kib -lt 1022976 ]; then
+      printf '%03dM' "`echo "scale=0; $rx_kib / 1024" | bc`"
+    else
+      printf "%sG" "`echo "scale=1; $rx_kib / 1024000" | bc`"
+    fi
+  fi
 else
   printf %03d ${rx_kib} # leading zeroes so length is constant
   echo -n "K"
@@ -102,7 +111,15 @@ echo -n " "
 echo -n "$OUTLABEL"
 tx_kib=$(( $tx_rate >> 10 ))
 if hash bc 2>/dev/null && [[ "$tx_rate" -gt 1048576 ]]; then
-  printf '%sM' "`echo "scale=1; $tx_kib / 1024" | bc`"
+  if [ $tx_kib -lt 9900 ]; then
+    printf '%sM' "`echo "scale=1; $tx_kib / 1024" | bc`"
+  else
+    if [ $tx_kib -lt 1022976 ]; then
+      printf '%03dM' "`echo "scale=0; $tx_kib / 1024" | bc`"
+    else
+      printf "%sG" "`echo "scale=1; $tx_kib / 1024000" | bc`"
+    fi
+  fi
 else
   printf %03d ${tx_kib}  # leading zeroes so length is constant
   echo -n "K"