Get Interface Speed In Linux Using Shell Script

Spread the love

Following is the shell script you can use to check the current throughput of network interface


while [ $var -eq 0 ]
tx=`cat /sys/class/net/$interface/statistics/tx_bytes`
rx=`cat /sys/class/net/$interface/statistics/rx_bytes`
sleep 1s
tx1=`cat /sys/class/net/$interface/statistics/tx_bytes`
rx1=`cat /sys/class/net/$interface/statistics/rx_bytes`

txw=`expr $tx1 – $tx`
rxw=`expr $rx1 – $rx`

echo “$txw:$rxw” | cat > /home/speed.txt

Please check $interface variable value. It should be the name of interface which you want to monitor. The speed values are stored in file “speed.txt” inside “/home/” directory. The value are stored as => Outgoing:Incoming. And the denomination is in bytes. You can modify it so that you can provide the interface name while calling the script.

Now to run the script as daemon use the “setsid” command in linux.

setsid >/dev/null 2>&1 < /dev/null &

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

To run the script at startup add following line to crontab

@reboot setsid >/dev/null 2>&1 < /dev/null &

Now your script will run at start time. But please give execution permission to your script

chmod +x