Merge branch 'master' of /tank/andrew/code/scripts
[scripts.git] / i3blocks-bandwidth.sh
index 26e5ac7ca656eea0d639db7da7f408162cced5cf..4c98e2f62742ca2341acc4c108a4ed24a900978f 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;;
@@ -83,28 +83,36 @@ tx_diff=$(( $tx - ${old[2]} ))
 rx_rate=$(( $rx_diff / $time_diff ))
 tx_rate=$(( $tx_diff / $time_diff ))
 
+round() {
+  echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
+}
+
+format() {
+  if [ $1 == 0 ]; then
+    printf '000K'
+  elif [ $1 -lt 999 ]; then
+    # printf '%sK' "$1";
+    printf %03d%s ${1%.*} K
+  elif [ $1 -lt 10240 ]; then
+    printf '%sM' "`echo "scale=1;$1 / 1024" | bc -l`"
+  elif [ $1 -lt 102400 ]; then
+    printf '0%sM' "$(round `echo "scale=1;$1 / 1024" | bc -l` 0)"
+  elif [ $1 -lt 1024000 ]; then
+    printf '%sM' "$(round `echo "scale=1;$1 / 1024" | bc -l` 0)"
+  else
+    printf '%sG' "$(round `echo "scale=2;$1 / 1048576" | bc -l` 1)"
+  fi
+}
+
 # shift by 10 bytes to get KiB/s. If the value is larger than
 # 1024^2 = 1048576, then display MiB/s instead
 
 # incoming
 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`"
-else
-  printf %03d ${rx_kib} # leading zeroes so length is constant
-  echo -n "K"
-fi
+format $(( $rx_rate >> 10 ))
 
 echo -n " "
 
 # outgoing
 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`"
-else
-  printf %03d ${tx_kib}  # leading zeroes so length is constant
-  echo -n "K"
-
-fi
+format $(( $tx_rate >> 10 ))