NicSpeed.bash – 1.2

Slight update folks to insure that the NIC has been passed as an argument.

#!/usr/bin/env bash
#
# @author:	Original Author Unknown - version 1.0
# @author:	Ricardo Wagemaker (["java"] + "@" + "wagemaker.co.uk") 2020-2021
# @name:	NicSpeed.bash
# @description: This shell script shows the network speed, both received and transmitted.
# @created: 	Sometime in 20st century but exact date unknown
# @updated: 	Sun  7 Feb 21:04:10 GMT 2021
# @Update:	CHECK_MARK, Calculate in MB, \r updated return characters to display B/s, KB/s & MB/s in a single line.
# @version:	1.2
#
# Usage: NicSpeed.bash interface
#
# Clear Screen
clear
#
# Make sure that NIC interface is specified
if [[ ${1} == "" ]]; then
	echo ""
	echo "Syntaxt: ${0} Interface"
	echo ""
	exit 0
fi

# Global variables
interface=$1
received_bytes=""
old_received_bytes=""
transmitted_bytes=""
old_transmitted_bytes=""
CHECK_MARK="\033[0;32m\xE2\x9C\x94\033[0m"


# 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 transmitted bytes.
function get_bytes
{
    line=$(cat /proc/net/dev | grep $interface | cut -d ':' -f 2 | awk '{print "received_bytes="$1, "transmitted_bytes="$9}')
    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.
function get_velocity
{
    value=$1    
    old_value=$2

    let vel=$value-$old_value
    let velKB=$vel/1000
    let velMB=$vel/1000/1000
	
    if [ $velMB != 0 ]; then
		echo -n "$velMB MB/s";
    elif [ $velKB != 0 ]; then
		echo -n "$velKB KB/s";
    else
		echo -n "$vel B/s";
    fi
}

# Gets initial values.
	get_bytes
	old_received_bytes=$received_bytes
	old_transmitted_bytes=$transmitted_bytes

# Shows a message and waits for one second.
	echo "Starting...";
	sleep 1;
	echo "";


# Main loop. It will repeat forever.
	while true; 
	do
# Get new transmitted and received byte number values.
	get_bytes
# Calculates speeds.
        vel_recv=$(get_velocity $received_bytes $old_received_bytes)
	vel_trans=$(get_velocity $transmitted_bytes $old_transmitted_bytes)
# Shows results in the console.

	echo -en "\r                                                         "
      	echo -en "\\r${CHECK_MARK} $interface DOWN:$vel_recv - UP:$vel_trans"

# Update old values to perform new calculations.
	old_received_bytes=$received_bytes
        old_transmitted_bytes=$transmitted_bytes
# Waits one second.
        sleep 1;

  	done
# END