-
Notifications
You must be signed in to change notification settings - Fork 19
/
netspeed
executable file
·86 lines (71 loc) · 2.42 KB
/
netspeed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env bash
# netspeed
# print the system's download and upload speed
# using /sys/class/net files
# stores a temporary file in HOME/.cache/netspeed
# uses formula SPEED = ( BYTES_NOW - BYTES_THEN (file) ) / TIME_DIFFERENCE
# this gives the average speed between this and last call
# to keep it close to instantaneous speed, keep call delta low (near to 1/sec)
# usage:
# netspeed [device name]
# device name - the name of the net adapter. Find yours using `ip link`
# ignore the lo (loopback device)
# if not providing device name on commandline arguments then make a file at
# HOME/.config/netspeed and store the device name in it
# example `echo "eth0" > ~/.config/netspeed" `
printspeed(){
speed=$1 # in bytes per second
# remove decimal
speed=${speed%.*}
speed=$((speed*8)) # convert to bits per second (bps)
kb=$((1000)) # using decimal ( 1kb = 1000b)
mb=$((kb*1000))
gb=$((mb*1000))
tb=$((gb*1000))
if [[ $speed -ge $tb ]]; then
printf "%2.0fT" "$((speed / tb))" # 1T = 1000G
elif [[ $speed -ge $gb ]]; then
printf "%2.0fG" "$((speed / gb))" # 1G = 1000M
else
printf "%2.0fM" "$((speed / mb))" # 1M = 1000K
fi
}
TMPFILE="$HOME/.cache/netspeed"
CONFFILE="$HOME/.config/netspeed"
if test -n "$1"; then DEV="$1";
elif test -e "$CONFFILE" && test -n "$(cat "$CONFFILE")"; then
DEV="$(cat "$CONFFILE")"
else
echo "Either create a ${CONFFILE} with device name, or pass device name as arguments"
echo "Maybe device name is $(netadn)"
echo "Usage $( basename "$0") [device name]"
exit 1
fi
RXFILE="/sys/class/net/$DEV/statistics/rx_bytes"
TXFILE="/sys/class/net/$DEV/statistics/tx_bytes"
if test -e "$TMPFILE" && test -n "$(cat "$TMPFILE")"; then
TMPDATA="$(cat "$TMPFILE")"
EPOCHOLD="$(echo "$TMPDATA" | cut -f 1)"
RXOLD="$(echo "$TMPDATA" | cut -f 2)"
TXOLD="$(echo "$TMPDATA" | cut -f 3)"
EPOCHNEW="$(date +%s.%N)"
RXNEW="$(cat "$RXFILE")"
TXNEW="$(cat "$TXFILE")"
EPOCHDIFF="$(bc <<< "$EPOCHNEW - $EPOCHOLD")" #seconds
RXDIFF="$(bc <<< "$RXNEW - $RXOLD")" #bytes
TXDIFF="$(bc <<< "$TXNEW - $TXOLD")" #bytes
UPSPEED="$(bc <<< "$TXDIFF / $EPOCHDIFF")" #bps
DOWNSPEED="$(bc <<< "$RXDIFF / $EPOCHDIFF")" #bps
printf ""
printspeed "$DOWNSPEED"
printf " "
printspeed "$UPSPEED"
echo
echo -e "$EPOCHNEW\t$RXNEW\t$TXNEW" > "$TMPFILE"
else
EPOCHNEW="$(date +%s.%N)"
RXNEW="$(cat "$RXFILE")"
TXNEW="$(cat "$TXFILE")"
echo -e "$EPOCHNEW\t$RXNEW\t$TXNEW" > "$TMPFILE"
$0
fi