Commits

Jason Ryan committed 606645a

Starting to refactor

Comments (0)

Files changed (1)

Scripts/netspeed.sh

-#!/bin/sh
-
-# This shell script shows the network speed, both received and transmitted.
-
+#!/usr/bin/env bash
+# Show the network speed, both received and transmitted.
 # Usage: net_speed.sh interface
-#   e.g: net_speed.sh eth0
 
 # Global variables
 interface=$1
 old_received_bytes=""
 transmitted_bytes=""
 old_transmitted_bytes=""
-cyan="\e[1;36;38m"
-green="\e[1;32;38m"
-magenta="\e[1;35;38m"
 
-# This function parses /proc/net/dev file searching for a line containing $interface data.
-# Within that line, the first and ninth numbers after ':' are respectively the received and transmited bytes.
-get_bytes()
-{
-    line=$(cat /proc/net/dev | grep $interface | cut -d ':' -f 2 | awk '{print "received_bytes="$1, "transmitted_bytes="$9}')
+blue=$'\e[1;36m'
+green=$'\e[1;34m'
+magenta=$'\e[1;35m'
+reset=$'\e[0m'
+
+get_bytes() {
+    local line=$(awk -v i=$interface '$1 ~ i {
+        print "received_bytes="$2, "transmitted_bytes="$9
+    }' /proc/net/dev) 
     eval $line
 }
 
-# Function which calculates the speed using actual and old byte number.
-# Speed is shown in KByte per second when greater or equal than 1 KByte per second.
-# This function should be called each second.
-get_velocity()
-{
-    value=$1
-    old_value=$2
+get_velocity() {
+    local value=$1
+    local old_value=$2
 
-    let vel=$value-$old_value
-    let velKB=$vel/1024
-    if [ $velKB != 0 ];
-    then
- echo -n "$velKB KB/s";
+    let vel="$value - $old_value"
+    let velKB="$vel / 1024"
+    if (( $velKB > 0 )); then
+        echo -n "$velKB KB/s"
     else
- echo -n "0 KB/s";
+        echo -n "0 KB/s"
     fi
 }
 
 old_transmitted_bytes=$transmitted_bytes
 
 # Shows a message and waits for one second.
-echo -e $magenta"NET SPEED";
-sleep 1;
-#echo "";
+echo -e "${magenta}NET SPEED${reset}"
+sleep 1
 
 # Main loop. It will repeat forever.
-while true;
-do
+while true; do
 
     # Get new transmitted and received byte number values.
     get_bytes
     vel_trans=$(get_velocity $transmitted_bytes $old_transmitted_bytes)
 
     # Shows results in the console.
-    echo -en $green"DOWN: $vel_recv"  $cyan"UP: $vel_trans\r"
+    echo -en ${green}"DOWN: $vel_recv"${reset}  $blue"UP: $vel_trans${reset}\r"
     # Update old values to perform new calculations.
     old_received_bytes=$received_bytes
     old_transmitted_bytes=$transmitted_bytes
 
-    # Waits one second.
     sleep 1;
-
 done
-